簡體   English   中英

LINQ到XML不返回任何結果可能的命名空間問題?

[英]linq to xml not returning any results possible namespace issue?

這是我的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>`

我正在嘗試使用下面的代碼提取文檔編號:

    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
                  };

但是,這不會返回任何結果。

我要去哪里錯了?

謝謝。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM