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);
}
最佳答案
我怀疑问题是您要从 document.Elements("url")
而不是 document.Root.Elements("url")
.. .所以它正在寻找 url
的 root 元素,该元素不存在。
试试这个:
List<string> urlList = doc.Root.Elements("url")
.Elements("loc")
.Select(x => (string) x)
.ToList();
请注意,我在这里没有使用 Descendants
,因为 loc
元素无论如何都直接位于 url
元素之下。
如果 only loc
元素无论如何都是正确的,您可以使用的另一种选择是:
List<string> urlList = doc.Descendants("loc")
.Select(x => (string) x)
.ToList();
(我假设 urlList
事先是空的......对于这种情况,我喜欢在整个操作中使用 LINQ 并消除 foreach
循环添加到集合中。)
编辑:代码对我有用。这是一个简短但完整的程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main(string[] args)
{
string 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>";
XDocument doc = XDocument.Parse(xml);
List<string> urlList = doc.Root
.Elements("url")
.Elements("loc")
.Select(x => (string) x)
.ToList();
Console.WriteLine(urlList.Count);
}
}
关于c# - 选择节点 Linq to Xml C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6965792/