c# - 选择节点 Linq to Xml C#

标签 c# xml linq linq-to-xml

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").. .所以它正在寻找 urlroot 元素,该元素不存在。

试试这个:

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/

相关文章:

c# - 更新键值对中Key的值

c# - 类设计悖论

c# - 如何强制关闭运行它自己的线程的后台 worker

c# - 从文本中删除 anchor 标记

xml - xsi :schemaLocation and pom. xml

java - Java 中极慢的 XSLT 转换

linq - linq 和 plinq 的区别

c# - 连接到 Azure 数据库的 Azure Function App C# HTTP 触发器

java - 如何将书籍的引用转换为 XML?

linq - 使用 LINQ 在单个查询中插入 2 个表