Linq to XML query not picking up any values

2019-08-28 02:18发布

问题:

I have an XML document that I'm trying to search through. The Main structure is as follows:

<?xml version="1.0"?>
<!DOCTYPE ONIXMessage SYSTEM "http://www.editeur.org/onix/2.1/reference/onix-international.dtd">
<ONIXMessage xmlns="http://www.editeur.org/onix/2.1/reference" release="2.1">
  <Header>
    <FromCompany>MyCo</FromCompany>
    <FromPerson>Joe Bloggs</FromPerson>
    <FromEmail>joe@bloggs.com</FromEmail>
    <SentDate>20120522</SentDate>
  </Header>
  <Product>
    <ProductForm>DG</ProductForm>
    <Title>
      <TitleType>01</TitleType>
      <TitleText>Blogg</TitleText>
    </Title>
    <WorkIdentifier>
      <WorkIDType>15</WorkIDType>
      <IDValue>PI3564231</IDValue>
    </WorkIdentifier>
    <Language>
      <LanguageRole>01</LanguageRole>
      <LanguageCode>eng</LanguageCode>
    </Language>
  </Product>
</ONIXMessage>

It's obviously shortened down for simplicity, but within the 'Product' tag, there is a lot more information. A File can also have any number of 'Product' tags.

I'm using linq to xml to search this document and take contents into my database, however my issue is that my query is not picking up any 'Product' tags in the file. Here is the snippet of code where the product should be picked up:

    XElement onix = XElement.Load(fs);
    // Get all the product information.
    //
    var products = from prod in onix.Elements("Product") select prod;

    foreach (var product in products)
    {
            //Process product
    }

Having debugged through the code, I can see that the variable 'onix' is being populated. I can see the entire contents of the file in that variable. 'products' however is not being populated.

Can anyone see if there's something I'm doing wrong?

回答1:

without namespace :

var products = onix.Descendants()
             .Where(m => m.Name.LocalName == "Product")
             .ToList();


回答2:

You need to add namespace

XElement onix = XElement.Load("test.xml");
XNamespace ns = "http://www.editeur.org/onix/2.1/reference";
var products = from prod in onix.Elements(ns+"Product") select prod;