使用VB.NET和LINQ To XML解析XML [英] Parsing XML with VB.NET with LINQ To XML

查看:71
本文介绍了使用VB.NET和LINQ To XML解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Web服务响应中收到一个传入XML流,看起来像这样

I have an incoming XML stream from a web service response that looks like so

<?xml version="1.0" encoding="utf-16"?>
<HotelPropertyDescriptionRS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" TimeStamp="2013-12-30T18:49:36" Version="1.14.1">
  <Success xmlns="http://webservices.sabre.com/sabreXML/2003/07" />
  <RoomStay xmlns="http://webservices.sabre.com/sabreXML/2003/07">
    <RoomRates>
      <RoomRate GuaranteeSurchargeRequired="G" IATACharacteristicIdentification="BGGO00" IATAProductIdentification="BLOOMBERG" RPH="001">
        <AdditionalInfo>
          <CancelPolicy Numeric="06" />
          <Commission NonCommission="true">NON COMMISSIONABLE</Commission>
          <Text>BLOOMBERG LP, 0.0 KM, INCLUDES BREAKFAST, INTERNET, WIFI, SEE</Text>
          <Text>RATE RULES DELUXE ROOM, GUEST ROOM, 1 KING OR 2 TWIN/SINGLE BE</Text>
        </AdditionalInfo>
        <Rates>
          <Rate Amount="66.600" CurrencyCode="KWD">
            <AdditionalGuestAmounts>
              <AdditionalGuestAmount MaxExtraPersonsAllowed="0">
                <Charges ExtraPerson="0" />
              </AdditionalGuestAmount>
            </AdditionalGuestAmounts>
            <HotelTotalPricing Amount="76.590">
              <Disclaimer>INCLUDES TAXES AND SURCHARGES</Disclaimer>
              <TotalSurcharges Amount="9.990" />
            </HotelTotalPricing>
          </Rate>
        </Rates>
      </RoomRate>
....

(将返回许多RoomRate值.我创建了一个类来保存需要从上述XML解析的值,

(there will be many RoomRate values returned. I have created a class to hold the values I need to parse from said XML which looks like so

Namespace Classes.Models
    Public Class RoomRate
        Public Property Rate() As String
        Public Property Surcharge() As String
        Public Property TotalPrice() As String
        Public Property CurrencyCode() As String
        Public Property CancellationPolicy() As String
        Public Property Disclaimer() As String
        Public Property Text() As List(Of String)
        Public Property Commission() As String
        Public Property GuaranteeSurchargeRequired() As String
        Public Property IATACharacteristicIdentification() As String
        Public Property IATAProductIdentification() As String
        Public Property RPH() As String
    End Class
End Namespace

现在,我不是要找人为我编写所有代码,而是要寻找一些想法,这将是将其解析为我的课堂的最有效方法.我可以使用XPathDocument和XPathNavigation& XPathNodeIterator类可以做到这一点(尚不能100%地确定它们如何工作),但是有更好的方法来完成此任务吗?

Now I'm not looking for someone to write all the code for me, I'm more looking for ideas on which would be the most efficient way to parse this into my class. I can use the XPathDocument and XPathNavigation & XPathNodeIterator classes to do this (not 100% sure how they work yet) but is there a better way to accomplish this task?

编辑

到目前为止,我已经提出了这个建议,这应该使我获得RoomRate元素中的第一个属性

I have come up with this so far, which should get me the first attributes in the RoomRate element

Return From el As XElement In _xDoc...<RoomRate>
               Select New RoomRate With { _
                   .GuaranteeSurchargeRequired = el...<RoomRate>.@GuaranteeSurchargeRequired, _
                   .IATACharacteristicIdentification = el...<RoomRate>.@IATACharacteristicIdentification, _
                   .IATAProductIdentification = el...<RoomRate>.@IATAProductIdentification, _
                   .RPH = el...<RoomRate>.@RPH}

现在我将如何遍历我提供的这段代码中的取消政策,房价和其他属性/元素?很抱歉有这么多问题,我真的很想学习正确的方法,并且能够正确地做到这一点.

Now how would I traverse to get say the cancellation policy, room rate and other attributes/elements within this code I provided? Sorry for so many questions, I really want to learn this the right way and be able to do it correctly.

编辑#2

我认为我在这里的方向正确:

I think I'm on the right track here:

Return From el As XElement In _xDoc...<RoomRate>
           Select New RoomRate With { _
               .GuaranteeSurchargeRequired = el.@GuaranteeSurchargeRequired, _
               .IATACharacteristicIdentification = el.@IATACharacteristicIdentification, _
               .IATAProductIdentification = el.@IATAProductIdentification, _
               .RPH = el.@RPH, _
               .CancellationPolicy = el...<AdditionalInfo>...<CancellationPolicy>.@Numeric, _
               .Commission = el...<AdditionalInfo>...<Commission>.@NonCommission}

有人可以让我知道我是否在正确的方向上完成这项工作?

Can someone let me know if I'm on the right track for accomplishing this?

编辑3

我已将代码更改为此

For Each n As XElement In _xDoc.Elements("RoomRate")
                    _rates.Add(New RoomRate With { _
                               .GuaranteeSurchargeRequired = n.Attribute("GuarateeSurchargeRequired").Value, _
                               .IATACharacteristicIdentification = n.Attribute("IATACharacteristicIdentification").Value, _
                               .IATAProductIdentification = n.Attribute("IATAProductIdentification").Value, _
                               .RPH = n.Attribute("RPH")})
                Next

虽然我不再遇到任何错误,但也没有得到任何返回的结果.

And while I'm no longer getting any errors, but am not getting any results returned as well.

编辑4 我对代码进行了以下更改,该代码应返回IEnumerable(Of RoomRate),但不返回任何内容(这是基于我上面发布的XML代码段)

EDIT 4 I have made the following changes t my code, which should return an IEnumerable(Of RoomRate) but it's returning nothing (this is based on the XML snippet i posted above)

Dim rates = From rate In _xDoc.Descendants("RoomRate")
                Select New RoomRate With { _
                    .GuaranteeSurchargeRequired = rate.Attribute("GuaranteeSurchargeRequired").Value, _
                    .IATACharacteristicIdentification = rate.Attribute("IATACharacteristicIdentification").Value, _
                    .IATAProductIdentification = rate.Attribute("IATAProductIdentification").Value, _
                    .RPH = rate.Attribute("RPH").Value}

看起来应该可以,我在这里做什么错了?

That looks like it should work, what am I doing wrong here?

编辑#5 @Neolisk我按照您的建议进行了更改,现在看起来像这样

EDIT #5 @Neolisk I made my changes the way you suggested, it now looks like so

For Each n As XElement In _xDoc.Descendants("RoomRate")
    rate = New RoomRate()
    rate.GuaranteeSurchargeRequired = n.Attribute("GuaranteeSurchargeRequired").Value
    rate.IATACharacteristicIdentification = n.Attribute("IATACharacteristicIdentification").Value
    rate.IATAProductIdentification = n.Attribute("IATAProductIdentification")
    _rates.Add(rate)
Next
Return _rates

但是它永远不会进入循环,直接进入返回_rates

But it never goes into the loop, it goes straight to Return _rates

编辑#6

好吧,我像这样填充了RoomRate元素的前3个属性

Ok I got it populating the first 3 attributes of the RoomRate element like this

Dim rate As RoomRate
Dim ns As XNamespace = "http://webservices.sabre.com/sabreXML/2003/07"
Dim rate As RoomRate
For Each n As XElement In _xDoc.Descendants(ns + "RoomRate")
    rate = New RoomRate()
    rate.GuaranteeSurchargeRequired = n.Attribute("GuaranteeSurchargeRequired").Value
    rate.IATACharacteristicIdentification = n.Attribute("IATACharacteristicIdentification").Value
    rate.IATAProductIdentification = n.Attribute("IATAProductIdentification").Value
    rate.RPH = n.Attribute("RPH").Value

    _rates.Add(rate)
Next

现在,当我尝试遍历文档的其余部分时,我会尝试像这样获得CancelPolicy值

Now when I try to traverse through the rest of the document I try and get the CancelPolicy value like so

Dim rate As RoomRate
Dim ns As XNamespace = "http://webservices.sabre.com/sabreXML/2003/07"
Dim rate As RoomRate
For Each n As XElement In _xDoc.Descendants(ns + "RoomRate")
    rate = New RoomRate()
    rate.GuaranteeSurchargeRequired = n.Attribute("GuaranteeSurchargeRequired").Value
    rate.IATACharacteristicIdentification = n.Attribute("IATACharacteristicIdentification").Value
    rate.IATAProductIdentification = n.Attribute("IATAProductIdentification").Value
    rate.RPH = n.Attribute("RPH").Value
    rate.CancellationPolicy = n.Element("AdditionalInfo").Element("CancelPolicy").Attribute("Numeric").Value

    _rates.Add(rate)
Next

但是添加最后一行会导致NullReferenceException.我现在将如何处理XML?

But adding that last line causes a NullReferenceException. How would I go about going through the XML now?

推荐答案

使用此代码解决了我的问题

Got my issue resolved with this code

Public Function ParseRates() As IEnumerable(Of RoomRate)
    Try
        Dim ns As XNamespace = "http://webservices.sabre.com/sabreXML/2003/07"
        Dim rate As RoomRate
        For Each n As XElement In _xDoc.Descendants(ns + "RoomRate")
            _rates.Add(New RoomRate With { _
                        .GuaranteeSurchargeRequired = n.Attribute("GuaranteeSurchargeRequired").Value, _
                        .IATACharacteristicIdentification = n.Attribute("IATACharacteristicIdentification").Value, _
                        .IATAProductIdentification = n.Attribute("IATAProductIdentification").Value, _
                        .RPH = n.Attribute("RPH").Value, _
                        .CancellationPolicy = n.Element(ns + "AdditionalInfo").Element(ns + "CancelPolicy").Attribute("Numeric").Value, _
                        .Commission = n.Element(ns + "AdditionalInfo").Element(ns + "Commission").Attribute("NonCommission").Value, _
                        .Rate = n.Element(ns + "Rates").Element(ns + "Rate").Attribute("Amount").Value, _
                        .CurrencyCode = n.Element(ns + "Rates").Element(ns + "Rate").Attribute("CurrencyCode").Value,
                        .TotalPrice = n.Element(ns + "Rates").Element(ns + "Rate").Element(ns + "HotelTotalPricing").Attribute("Amount").Value, _
                        .Disclaimer = n.Element(ns + "Rates").Element(ns + "Rate").Element(ns + "HotelTotalPricing").Element(ns + "Disclaimer").Value, _
                        .Surcharge = n.Element(ns + "Rates").Element(ns + "Rate").Element(ns + "HotelTotalPricing").Element(ns + "TotalSurcharges").Attribute("Amount").Value})
        Next
        Return _rates
    Catch ex As Exception
        ErrorMessage = ex.Message
        Return Nothing
    End Try
End Function

也许有一天我会找到一种更有效的方法来实现这一目标

Maybe someday I'll find a more efficient way to accomplish this

这篇关于使用VB.NET和LINQ To XML解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆