Question

Here are the first few lines of my XML document:

<?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>`

I am trying to extract the doc-number using the code below:

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

However this does not return any results.

Where am I going wrong?

Thanks.

Was it helpful?

Solution

The namespace of doc-number is http://www.epo.org/exchange. It has been inherited from the root node. You need to specify that in your query. Furthermore, doc-number isn't an element - i.e. direct child - of exchange-document. It is a descendant.

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

Please note that I changed exchange.Attribute("kind").Equals("A1") to (string)exchange.Attribute("kind") == "A1" and exchange.Descendant(d + "doc-number").Value to (string)exchange.Descendant(d + "doc-number").

That prevents NullReferenceExceptions if the attribute or descendant doesn't exist.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top