选择节点 Linq to Xml C#
XML 文件格式:
<?xml version="1.0" encoding="UTF-8"?>
<urlset>
<url>
<loc>element1</loc>
<changefreq>daily</changefreq>
<priority>0.2</priority>
</url>
<url>
<loc>element2</loc>
<changefreq>daily</changefreq>
<priority>0.2</priority>
</url>
<urlset>
我想选择所有“loc”节点(element1、element2),但这不起作用!
foreach (XElement item in document.Elements("url").Descendants("loc")) // Change into what?
{
urlList.Add(item.Value);
}
XML file format:
<?xml version="1.0" encoding="UTF-8"?>
<urlset>
<url>
<loc>element1</loc>
<changefreq>daily</changefreq>
<priority>0.2</priority>
</url>
<url>
<loc>element2</loc>
<changefreq>daily</changefreq>
<priority>0.2</priority>
</url>
<urlset>
I want to select all "loc" nodes (element1, element2), but this not work!!!
foreach (XElement item in document.Elements("url").Descendants("loc")) // Change into what?
{
urlList.Add(item.Value);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑问题是您要从
document.Elements("url")
而不是document.Root.Elements("url")
...所以它是正在查找url
的 root 元素,但该元素不存在。试试这个:
请注意,我在这里没有使用“后代”,因为
loc
元素都直接位于url
元素下方。如果 only
loc
元素无论如何都是正确的,您可以使用的另一种替代方法是:(我假设
urlList
事先是空的。 ..对于这种情况,我喜欢使用 LINQ 进行整个操作,并消除只是添加到集合中的foreach
循环。)编辑:该代码对我有用。这是一个简短但完整的程序:
I suspect the problem is that you're going from
document.Elements("url")
instead ofdocument.Root.Elements("url")
... so it's looking for a root element ofurl
, which doesn't exist.Try this:
Note that I haven't used
Descendants
here, as theloc
elements are all directly beneathurl
elements anyway.Another alternative you could use if the only
loc
elements are the right ones anyway, is just:(I'm assuming
urlList
was empty beforehand... for this sort of situation I like to use LINQ for the whole operation and eliminateforeach
loops that are just adding to a collection.)EDIT: The code works for me. Here's a short but complete program:
试试这个:
Try this: