0

我有这种结构的 XML 文档:

<dipOrders>
    <interchangeInfo senderEdiCode="LSC58" senderEdiCodeQal="ZZ" receiverEdiCode="15274" receiverEdiCodeQal="ZZ" syntax="X12" syntaxId="X" syntaxVersion="003010"/>
    <order orderNumber="219299" orderDate="2012-12-05T00:00:00" validityDate="2012-12-05T00:00:00">
        <buyer name="LEAR MTO">
            <partyCode buyerCode="811567924"/>
        </buyer>
        <supplier name="BRIDGE OF WEIR LEATHER CO">
            <partyCode buyerCode="749630"/>
        </supplier>
        <orderConsignee name="LEAR MEXICAN SEATING CORP">
            <partyCode buyerCode="LSC59"/>
            <orderLine description="LEA DC 378 HERO 6RSB 5B8" orderNumber="246767" engineeringChangeNumber="N">
                <partyCode buyerCode="DC378105H6RSB5B8AA"/>
                <cumulativeQuantity date="2012-12-04T00:00:00" quantity="0"/>
                <orderQuantity quantity="0" commitmentLevel="Firm" timingQualifier="Weekly" shipDate="2012-12-05T00:00:00"/>
            </orderLine>
            <orderLine description="LEA DC 378 HERO 6RSB 5V0" orderNumber="246767" engineeringChangeNumber="N">
                <partyCode buyerCode="DC378105H6RSB5V0AA"/>
                <cumulativeQuantity date="2012-12-04T00:00:00" quantity="0"/>
                <orderQuantity quantity="0" commitmentLevel="Firm" timingQualifier="Weekly" shipDate="2012-12-05T00:00:00"/>
            </orderLine>

我正在尝试在 .NET 控制台应用程序中使用 Linq to XML 访问它以获取 orderLine 项目详细信息:

XDocument doc = XDocument.Load(sourceDirectory + "\\" + fileName);

                var data = from item in doc.Descendants("orderLine")
                           select new
                           {
                               orderNumber = item.Element("orderNumber").Value
                           };

                foreach (var i in data)
                {
                    Console.WriteLine(i.ToString());
                }

                Console.ReadLine();

但我得到“对象引用未设置为对象的实例”错误。为什么?

4

1 回答 1

3

您正在尝试从元素中获取orderNumber 元素orderLine......但它是一个属性。顺便说一下,不清楚为什么要从中创建匿名类型 - 或者为什么要使用查询表达式开始。我会这样写:

var orderNumbers = doc.Descendants("orderLine")
                      .Select(x => (int) x.Attribute("orderNumber"));
foreach (int orderNumber in orderNumbers)
{
    Console.WriteLine(orderNumber);
}
于 2013-01-16T09:52:58.497 回答