linq to xml没有返回任何结果可能的命名空间问题?

时间:2013-04-23 14:34:57

标签: c# xml linq xelement

以下是我的XML文档的前几行:

<?xml-stylesheet type="text/xsl" href="/3.0/style/exchange.xsl"?>
<ops:world-patent-data xmlns="http://www.epo.org/exchange" xmlns:ops="http://ops.epo.org" xmlns:xlink="http://www.w3.org/1999/xlink">
<ops:meta name="elapsed-time" value="83" />
<exchange-documents>
<exchange-document system="ops.epo.org" family-id="34916979" country="EP" doc-number="1726228" kind="A1">
  <bibliographic-data>
    <publication-reference>
      <document-id document-id-type="docdb">
        <country>EP</country>
        <doc-number>1726228</doc-number>`

我正在尝试使用以下代码提取doc-number:

    public class biblio
    {
        public string appNumber { get; set; }
    }

    XElement xDoc = XElement.Load(@"pathToMyXml.xml");
        XNamespace xn = "http://ops.epo.org";
        var bib = from exchange in xDoc.Descendants(xn + "exchange-document")
                  where exchange.Attribute("kind").Equals("A1")
                  select new biblio
                  {
                      appNumber = exchange.Element("doc-number").Value
                  };

然而,这不会返回任何结果。

我哪里错了?

感谢。

1 个答案:

答案 0 :(得分:0)

doc-number的命名空间为http://www.epo.org/exchange。它已从根节点继承。您需要在查询中指定它。此外,doc-number不是exchange-document的元素 - 即直接子元素。它是后代。

XNamespace d = "http://www.epo.org/exchange";
var bib = from exchange in xDoc.Descendants(xn + "exchange-document")
          where (string)exchange.Attribute("kind") == "A1"
          select new biblio
          {
              appNumber = (string)exchange.Descendant(d + "doc-number")
          };

请注意,我将exchange.Attribute("kind").Equals("A1")更改为(string)exchange.Attribute("kind") == "A1",将exchange.Descendant(d + "doc-number").Value更改为(string)exchange.Descendant(d + "doc-number")

如果属性或后代不存在,则会阻止NullReferenceException