xml响应http post - 将request.inputstream转换为string - asp.net

时间:2012-06-18 23:53:03

标签: asp.net xml xml-parsing linq-to-xml

我收到了xml响应,现在我想解析它。

目前我收到的XML响应是:

    Dim textReader = New IO.StreamReader(Request.InputStream)

    Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
    textReader.DiscardBufferedData()

    Dim Xmlin = XDocument.Load(textReader)

我现在如何继续进行此过程并选择元素值?

<subscription>
<reference>abc123</reference>
<status>active</status>
<customer>
    <fname>Joe</fname>
    <lname>bloggs</lname>
    <company>Bloggs inc</company>
    <phone>1234567890</phone>
    <email>joebloggs@hotmail.com</email>
 </customer>
 </subscription>

如果我以字符串格式使用它,我可以使用

执行此操作
    Dim xmlE As XElement = XElement.Parse(strXML) ' strXML is string version of XML

    Dim strRef As String = xmlE.Element("reference")

我是否需要将request.inputstream转换为strign格式,还是有另一种更好的方式?

由于

2 个答案:

答案 0 :(得分:1)

  

我是否需要将request.inputstream转换为strign格式,还是有另一种更好的方式?

您可以直接从请求流加载它,您不需要将其转换为字符串:

Request.InputStream.Position = 0
Dim Xmlin = XDocument.Load(Request.InputStream)
Dim reference = Xmlin.Element("subscription").Element("reference").Value

或:

Dim reference = Xmlin.Descendants("reference").First().Value

答案 1 :(得分:1)

经过多次测试后,我终于可以开始工作了:

    Dim textReader = New IO.StreamReader(Request.InputStream)

    Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
    textReader.DiscardBufferedData()

    Dim Xmlin = XDocument.Load(textReader)

    Dim strXml As String = Xmlin.ToString

    Dim xmlE As XElement = XElement.Parse(strXml)
    Dim strRef As String = xmlE.Element("reference")
    Dim strStatus As String = xmlE.Element("status")
    Dim strFname As String = xmlE.Element("customer").Element("fname").Value()
    Dim strLname As String = xmlE.Element("customer").Element("lname").Value()
    Dim strCompany As String = xmlE.Element("customer").Element("company").Value()
    Dim strPhone As String = xmlE.Element("customer").Element("phone").Value()
    Dim strEmail As String = xmlE.Element("customer").Element("email").Value()