【问题标题】:xml response http post - convert request.inputstream to string - asp.netxml 响应 http post - 将 request.inputstream 转换为字符串 - asp.net
【发布时间】:2012-06-21 00:03:24
【问题描述】:

我收到一个 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 格式还是有其他更好的方法?

谢谢

【问题讨论】:

  • 使用 XmlDocument。有了它,你可以用 url 调用它的load 方法,它会很好地把它拉下来。 Read more...
  • 不仅是 XmlDocument,而且一旦你进入它,你就可以使用 LINQ 来获取数据,甚至可能更快。
  • 但是,我不得不问你为什么会这样接收它,因为如果你愿意,我们当然可以将它作为输入的 XML 接收
  • 嗨,有点不确定...我将其作为 http 发布响应接收。看着这个问题,似乎是要走的路:stackoverflow.com/questions/2816168/…

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


【解决方案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()

【讨论】:

    【解决方案2】:

    我需要将 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
    

    【讨论】:

    • 是的,这就是我的原始解决方案的要点,正如 OP 所链接的那样!
    • 特别想用VB.NET的轴查询:xmlIn.&lt;subscription&gt;.&lt;reference&gt;.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2018-08-29
    相关资源
    最近更新 更多