如何用LINQ解析这个xml

时间:2013-12-27 13:34:48

标签: .net xml vb.net linq

我的XML有多个元素但是当我尝试使用LINQ解析它们时,我只得到一个元素。我的选择陈述有些不对劲,但我有一段时间了解错误。对于所有(2)InvoiceUid

,结果应该是填充了InvoiceNumberinvoiceListItems的字典

这是我的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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

啊,最后通过添加.Elements来实现它:

For Each InvoiceListItem In InvoiceListItems.Elements