与LINQ读取XML文件到XML
问题描述:
我有一点XML放入一个字符串,叫做为myContent:与LINQ读取XML文件到XML
<People xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person ID="1" name="name1" />
<Person ID="2" name="name2" />
(....)
<Person ID="13" name="name13" />
<Person ID="14" name="name14" />
</People>
,并在C#我已经存储了先前的XML内容的字符串变量象下面这样:
private string myContent = String.Empty +
"<People xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<Person ID=\"1\" name=\"name1\" />" +
"<Person ID=\"2\" name=\"name2\" />" +
(...)
"<Person ID=\"13\" name=\"name13\" />" +
"<Person ID=\"14\" name=\"name14\" />" +
"</People>";
和我加载如下:
XDocument contentXML = XDocument.Parse(myContent);
然后我遍历所有的人:
IEnumerable<XElement> people = contentXML.Elements();
foreach (XElement person in people)
{
var idPerson = person.Element("Person").Attribute("ID").Value;
var name = person.Element("Person").Attribute("name").Value
// print the person ....
}
问题是我只获得第一个人,而不是其他人。它说人们有1个元素,它应该有14.
任何想法?
答
问题是您要求文档根目录下的Elements()
。此时只有一个元素,People
。
你真正想要做的是一样的东西:
var people = contentXML.Element("People").Elements()
因此,你的循环看起来是这样的:
IEnumerable<XElement> people = contentXML.Element("People").Elements();
foreach (XElement person in people)
{
var idPerson = person.Attribute("ID").Value;
var name = person.Attribute("name").Value;
// print the person ....
}
,你打算这将遍历每个Person
元素。
+0
就像你说的,元素(“人物”)在contentXML和Elements()之间错过了。现在,它的工作,谢谢! – user1624552 2013-05-14 20:02:49
+0
@ user1624552:非常欢迎。有时候很容易错过这些东西。 – 2013-05-15 14:22:04
为什么你在开始时有一个String.Empty? – CloudyMarble 2013-05-14 12:41:09
它不是必需的String.empty,但你认为是原因吗? – user1624552 2013-05-14 12:43:19
可能是,代码对我来说看起来不错 – CloudyMarble 2013-05-14 12:46:28