这是代码片段:
XDocument themes = XDocument.Load(HttpContext.Current.Server.MapPath("~/Models/Themes.xml"));
string result = "";
var childType = from t in themes.Descendants()
where t.Attribute("name").Value.Equals(theme)
select new { value = t.Attribute("type").Value };
foreach (var t in childType) {
result += t.value;
}
return result;
这是 XML:
<?xml version="1.0" encoding="utf-8" ?>
<themes>
<theme name="Agile">
<root type="Project">
<node type="Iteration" >
<node type="Story">
<node type="Task"/>
</node>
</node>
</root>
</theme>
<theme name="Release" >
<root type="Project">
<node type="Release">
<node type="Task" />
<node type="Defect" />
</node>
</root>
</theme>
</themes>
我究竟做错了什么?我不断收到“对象未设置为对象实例”异常。
我试图返回的是基于父节点类型的所选节点的类型,即,如果主题是“Agile”并且父节点是“Project”,那么返回值应该是“Iteration”。这是最终的结果,但我从来没有走到那一步,因为我被你上面看到的困住了。
我想你想要更接近这个的东西:
XDocument themes = XDocument.Load(HttpContext.Current.Server.MapPath("~/Models/Themes.xml"));
string result = "";
var childType = from t in themes.Descendants("theme")
where t.Attribute("name").Value.Equals(theme)
select new { value = t.Descendants().Attribute("type").Value };
foreach (var t in childType) {
result += t.value;
}
return result;
EDIT:根据您的附加信息,也许这更接近:
XDocument themes = XDocument.Load(HttpContext.Current.Server.MapPath("~/Models/Themes.xml"));
string result = "";
var childType = from t in themes.Descendants("theme")
where t.Attribute("name").Value.Equals(theme)
where t.Element("node").Attribute("type").Value == parent
select new { value = t.Descendants().Attribute("type").Value };
foreach (var t in childType) {
result += t.value;
}
return result;
编辑2:这对我有用:
XDocument themes = XDocument.Load(HttpContext.Current.Server.MapPath("~/Models/Themes.xml"));
string result = "";
var theme = "Agile";
var parent = "Project";
var childType = from t in themes.Descendants("theme")
where t.Attribute("name").Value.Equals(theme)
where t.Element("root").Attribute("type").Value == parent
from children in t.Element("root").Descendants()
select new { value = children.Attribute("type").Value };
foreach (var t in childType) {
result += t.value;
}
return result;
EDIT 3:这是完整的工作程序,只需将其放入控制台应用程序的类中即可。
static void Main(string[] args)
{
var xml = "<themes><theme name='Agile'><root type='Project'><node type='Iteration' ><node type='Story'><node type='Task'/></node></node></root></theme><theme name='Release' ><root type='Project'><node type='Release'><node type='Task' /><node type='Defect' /></node></root></theme></themes>";
XDocument themes = XDocument.Parse(xml);
string result = "";
var theme = "Agile";
var parent = "Project";
var childType = from t in themes.Descendants("theme")
where t.Attribute("name").Value.Equals(theme)
where t.Element("root").Attribute("type").Value == parent
from children in t.Element("root").Descendants()
select new { value = children.Attribute("type").Value };
foreach (var t in childType)
{
Console.WriteLine(t.value);
}
Console.Read();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)