【问题标题】:How to retrieve descendants using Linq如何使用 Linq 检索后代
【发布时间】:2015-09-30 06:50:47
【问题描述】:

我有一个 xml,我在其中循环遍历每个 node 并且我想检索 xhtml 元素并且我尝试过

foreach (XElement element in xdoc.Descendants(namespace))
{
  var result = element.Descendants(namespace + "xhtml")
}

但枚举总是返回empty

数据:

<namespace xmlns="http://www.find.org/schemas/">
  <date>2015</date>
  <xhtml:link xmlns:xhtml="xhtml:link" rel="alternate" />
  <xhtml:link xmlns:xhtml="xhtml:link" rel="alternate" />
  <xhtml:link xmlns:xhtml="xhtml:link" rel="alternate" />
</namespace>

【问题讨论】:

  • 您还没有发布xhtml 的命名空间,必须为它定义一个命名空间,例如xmlns:xhtml:"http://foo"
  • @Rahul Singh 我没听懂你,你能发一个 samplr

标签: c# xml linq linq-to-xml xml-namespaces


【解决方案1】:

您的链接元素位于其自己的命名空间中,在命名空间xhtml:link 中称为xhtml。您需要使用它来选择元素。

 // namespace of yout document
 var ns = (XNamespace) "http://www.find.org/schemas"; 
 // namespace of link elements
 var nsXhtml = (XNamespace) "xhtml:link";

 var result = xdoc.Root.Elements(nsXhtml+ "link");
 result.Dump();

在 xml 文档中,您应该注意 xmlns: 构造,它们可以位于顶部或定义在元素上。使用 no 或错误的命名空间将找不到您的元素。

【讨论】:

    【解决方案2】:

    试试这个

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string input =
                    "<namespace xmlns=\"http://www.find.org/schemas/\">" +
                      "<date>2015</date>" +
                      "<xhtml:link xmlns:xhtml=\"xhtml:link\" rel=\"alternate\" />" +
                      "<xhtml:link xmlns:xhtml=\"xhtml:link\" rel=\"alternate\" />" +
                      "<xhtml:link xmlns:xhtml=\"xhtml:link\" rel=\"alternate\" />" +
                    "</namespace>";
    
                XDocument xdoc = XDocument.Parse(input);
    
                List<XElement> links = xdoc.Descendants().Where(x => x.Name.LocalName == "link").ToList();
            }
        }
    }​
    

    【讨论】:

      猜你喜欢
      • 2012-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多