【问题标题】:how to parse this xml with LINQ如何用 LINQ 解析这个 xml
【发布时间】:2013-12-27 13:34:48
【问题描述】:

我的 XML 有多个元素,但是当我尝试使用 LINQ 解析它们时,我只得到一个元素。我的 select 语句出了点问题,但我有一段时间了解出了什么问题。结果应该是一个字典,其中包含所有 (2) invoiceListItemsInvoiceUidInvoiceNumber

这是我的 XML:

    <?xml version="1.0" encoding="utf-8"?>
    <invoiceListResponse>
      <invoiceList>
        <invoiceListItem>
          <invoiceUid>39165890</invoiceUid>
          <invoiceDate>2013-12-26</invoiceDate>
          <invoiceNumber>W10001888</invoiceNumber>
          <contactUid>8363070</contactUid>
        </invoiceListItem>
        <invoiceListItem>
          <invoiceUid>39149309</invoiceUid>
          <invoiceDate>2013-12-24</invoiceDate>
          <invoiceNumber>W100</invoiceNumber>
          <contactUid>8363070</contactUid>
        </invoiceListItem>
      </invoiceList>
    </invoiceListResponse>

还有我的代码:

         Dim list As XmlDocument = proxy.Find(queries)

        Dim InvoiceList = XDocument.Parse(list.InnerXml)
        ' get all <InvoiceListItem> elements from the xdocumetn
        Dim InvoiceListItems = From invoiceListItem In InvoiceList...<invoiceList>
                                 Select invoiceListItem

        'go through each InvoiceListItem in InvoiceListItems
        For Each InvoiceListItem In InvoiceListItems
            Console.WriteLine("Uid is {0} and Invoice Number is {1}", InvoiceListItem...<invoiceUid>.Value, InvoiceListItem...<invoiceNumber>.Value)
            returnInvoiceList.Add(InvoiceListItem...<invoiceNumber>.Value, CType(InvoiceListItem...<invoiceUid>.Value, Integer))
        Next
        Return returnInvoiceList

【问题讨论】:

    标签: .net xml vb.net linq


    【解决方案1】:

    问题是您的 select 语句正在选择 invoiceList 元素(其中只有一个)。这应该符合您的预期:

    Dim InvoiceListItems = From invoiceListItem In InvoiceList...<invoiceListItem>
                           Select invoiceListItem
    

    【讨论】:

      【解决方案2】:

      啊终于通过在此处添加 .Elements 使其工作:

      For Each InvoiceListItem In InvoiceListItems.Elements
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-30
        • 1970-01-01
        • 2012-02-27
        • 1970-01-01
        • 2014-05-01
        • 1970-01-01
        • 2015-04-17
        • 1970-01-01
        相关资源
        最近更新 更多