用于解析XML的内联VB

时间:2017-05-30 17:43:54

标签: xml vb.net inline

我有一个XML Feed,我将其作为对Web服务调用的响应返回:

<?xml version="1.0" encoding="utf-8"?>
    <CustomerGetResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://WHATEVER/webservice">
    <UserExists>false</UserExists>
    <DisableAccountFlag>false</DisableAccountFlag>
</CustomerGetResult>

我接受该响应并将其存储为名为:strRead的字符串。然后我尝试使用以下方法获取值(没有成功):

Dim XMLString = XDocument.Parse(strRead)
Response.Write("UserExists: " & XMLString.<CustomerGetResult>.<UserExists>.Value)
Response.Write("DisableAccountFlag: " & XMLString.<CustomerGetResult>.<DisableAccountFlag>.Value)

我也尝试过其他方法但没有成功:

Dim doc As New System.Xml.XmlDocument()
doc.LoadXML(strRead)
dim SymbolText as String = doc.SelectSingleNode("//CustomerGetResult/UserExists").Value
Response.Write(SymbolText)

此时有人可以帮助我吗?这是在aspx文件中的内联。

2 个答案:

答案 0 :(得分:0)

命名空间是关键:

Dim myNamespace As XNamespace = YourXMLNameSpace

For Each report As XElement In xmlr.Descendants(myNamespace + "CustomerGetResult")
  Console.WriteLine(report.Element(myNamespace + "UserExists").Value)
Next

答案 1 :(得分:0)

以下是两个选择

        Dim strRead = "<?xml version=""1.0"" encoding=""utf-8""?>" & _
            "<CustomerGetResult xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://WHATEVER/webservice"">" & _
            "<UserExists>false</UserExists>" & _
            "<DisableAccountFlag>false</DisableAccountFlag>" & _
        "</CustomerGetResult>"

        Dim XMLString As XDocument = XDocument.Parse(strRead)
        Dim root As XElement = XMLString.Root
        Dim ns As XNamespace = root.GetDefaultNamespace()

        'Method 1
        Console.WriteLine("UserExists: {0}", CType(XMLString.Descendants(ns + "UserExists").FirstOrDefault(), String))
        Console.WriteLine("DisableAccountFlag: {0}", CType(XMLString.Descendants(ns + "DisableAccountFlag").FirstOrDefault(), String))

        'Method 2
        Console.WriteLine("UserExists: {0}", CType(XMLString.Descendants().Where(Function(x) x.Name.LocalName = "UserExists").FirstOrDefault(), String))
        Console.WriteLine("DisableAccountFlag: {0}", CType(XMLString.Descendants().Where(Function(x) x.Name.LocalName = "DisableAccountFlag").FirstOrDefault(), String))