简体   繁体   English

Linq to XML查询未获取任何值

[英]Linq to XML query not picking up any values

I have an XML document that I'm trying to search through. 我有一个要搜索的XML文档。 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. 我正在使用linq到xml来搜索该文档并将内容带入数据库,但是我的问题是我的查询没有在文件中拾取任何“产品”标签。 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. 通过代码调试之后,我可以看到正在填充变量“ onix”。 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? 谁能看到我在做错什么吗?

without namespace : 没有命名空间:

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

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM