【问题标题】:Get values of XDocument获取 XDocument 的值
【发布时间】:2014-01-13 17:10:23
【问题描述】:

我知道我们有很多关于 xml 的主题,但我无法让它发挥作用。 我有这个 xml:

<OrderRoot>
   <Order>
     <Client>Company Company</Client>
     <Cod>0000</Cod>
   </Order>
   <Itens>
     <Item Sequence="01">
       <Product>54321</Product>
       <Description>xxxxxxx</Description>
     </Item>
     <Item Sequence="02">
       <Product>12345</Product>
       <Description>xxxxxxx</Description>
     </Item>
     <Item Sequence="03">
       <Product>123456</Product>
       <Description>xxxxxxx</Description>
     </Item>      
   </Itens>
 </OrderRoot>

我的代码:

   order.Client = xmlDocument.Descendants("Client").First().Value;
   order.A1_Codigo = xmlDocument.Descendants("Cod").First().Value;

   foreach (XElement item in xmlDocument.Descendants("Itens"))
   {
       //EDITed
       var aux = item.Element("Product").Value; //Get the null reference exception here.
   }

但我总是在 foreach 循环中获得系统空引用。之前的顺序工作正常。

我在这里做错了什么?

【问题讨论】:

  • pedido 到底在哪里定义?因为现在,那是你的空引用。
  • 对不起,我编辑了。 Order 是一个对象,其中包含一个 item 列表和其他属性。
  • 好的,调试你的代码并找出什么是空的以及为什么。有了这么小的窗口,我们很难非常告诉您出了什么问题。你甚至没有告诉我们哪一行和什么对象是空的。
  • 你有没有按顺序实例化Itens属性?
  • 是的,我在构造函数中有它。

标签: c# .net xml linq-to-xml


【解决方案1】:

Product 不是 Itens 的直接子代,这就是您遇到异常的原因。尝试更改循环源:

foreach (XElement item in xmlDocument.Descendants("Itens").Elements("Item"))

【讨论】:

    猜你喜欢
    • 2012-04-23
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    相关资源
    最近更新 更多