【问题标题】:How to query an XDocument with LINQ when elements have a colon in their name?当元素的名称中有冒号时,如何使用 LINQ 查询 XDocument?
【发布时间】:2009-10-28 21:04:50
【问题描述】:

我正在尝试在 XDocument 对象中使用 LINQ to XML。下例中如何查询结果元素?

<serv:header>
   <serv:response>
      <serv:result>SUCCESS</serv:result>
      <serv:gsbStatus>PRIMARY</serv:gsbStatus>
   </serv:response>
</serv:header>

当我使用这样的语句时,我得到异常'附加信息:':'字符,十六进制值 0x3A,不能包含在名称中。'

XDocument doc = XDocument.Parse(xml);
string value = doc.Descendants("serv:header").First().Descendants("serv:response").First().Descendants("serv:result").First().Value;

【问题讨论】:

    标签: linq linq-to-xml


    【解决方案1】:

    serv 在您的 XML 中是一个 命名空间前缀。它必须与一些标识命名空间的 URI 相关联。在你的 XML 中寻找这样的属性:

    xmlns:serv="..."
    

    引号内的值将是命名空间。现在,在您的 C# 代码中,您使用该 URI 创建一个 XNamespace 对象:

    private static readonly XNamespace serv = "...";
    

    然后你可以在这样的查询中使用它:

    string value = doc
        .Descendants(serv + "header").First()
        .Descendants(serv + "response").First()
        .Descendants(serv + "result").First()
        .Value;
    

    顺便说一句,你应该考虑使用.Element()而不是.Descendants().First()

    【讨论】:

    • 我可以使用doc.Root.GetNamespaceOfPrefix("serv")
    • 在我的实现中修剪脂肪,我能够在我的目标方法中创建一个更简单的变量:XNamespace xd = @"http://...";
    【解决方案2】:

    该冒号表示 XML 正在使用 namespaces。基于此 blogpost 某人发布了有关 LINQ、XML 和命名空间的帖子,这是您可能想尝试的代码版本。:

    static XName serv(string name)
    {
      return XNamespace.Get("<THE_NAMESPACE_URL>") + name;
    }
    
    XDocument doc = XDocument.Parse(xml);
    string value = doc.Descendants(serv("header")).First().Descendants(serv("response")).First().Descendants(serv("result")).First().Value;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多