我在windows手机的应用程序中解析xml。 我的XML看起来像这样:
<?xml version="1.0" encoding="utf-8" ?>
<people>
<person name="Kurt Cobain">
<overall>
</overall>
<childhood>
</childhood>
<youth>
</youth>
<picture1>
</picture1>
</person>
</people>
我应该得到人员节点的元素名称(整体,童年,青年等),因为对于每个人节点,他们将是不同的。 到目前为止,这是我的代码,但查询结果为null:
XDocument loadedXml = XDocument.Load("people.xml");
var data = from query in loadedXml.Descendants("person")
where ((query.Attribute("name").Value as string).Equals("Kurt Cobain"))
select query.Elements();
string test = "";
foreach (var item in data)
{
test + = (item as XElement).Name.LocalName;
}
MessageBox.Show(test);
答案 0 :(得分:2)
var data = from item in loadedXml.Descendants("person")
where ((item.Attribute("name").Value as string).Equals("Kurt Cobain"))
select item;
string test = "";
foreach (var item in data)
test += item.Attribute("name").Value;
答案 1 :(得分:2)
从你的linq中删除.Elements()
。
var data = from query in loadedXml.Descendants("person")
where ((query.Attribute("name").Value as string).Equals("Kurt Cobain"))
select query;
答案 2 :(得分:1)
我看到您尝试在代码的一部分中使用XElement,其他建议应该有效,但您也可以执行以下操作:
XElement loadedXml = XElement.Load("people.xml");
string test = "";
foreach (var item in loadedXml.XPathSelectElements("person[@name='Kurt Cobain']"))
{
test += item.Attribute("name").Value;
}
或者你可以这样做(这使得很难阅读)。
XElement loadedXml = XElement.Load("people.xml");
string test = loadedXml.XPathSelectElements("person[@name='Kurt Cobain']").Aggregate("", (current, item) => current + item.Attribute("name").Value);