我正在尝试读取Xml数据并将其加载到String of List中。但是我无法完成它。以下是我的代码。
昏暗的结果As String =“”
Dim soap As String = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCr & vbLf & "<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" " & vbCr & vbLf & " xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" " & vbCr & vbLf & " xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">" & vbCr & vbLf & " <soap:Body>" & vbCr & vbLf & " <Register xmlns=""http://tempuri.org/"">" & vbCr & vbLf & " <id>123</id>" & vbCr & vbLf & " <data1>string</data1>" & vbCr & vbLf & " </Register>" & vbCr & vbLf & " </soap:Body>" & vbCr & vbLf & "</soap:Envelope>"
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://localhost:59924/WebService.asmx/HelloWorld"), HttpWebRequest)
req.Headers.Add("SOAPAction", """http://tempuri.org/Register""")
req.ContentType = "text/xml;charset=""utf-16"""
req.Accept = "text/xml"
req.Method = "POST"
'req.ContentLength = strCritera.Length
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Dim requestWriter As New StreamWriter(req.GetRequestStream())
requestWriter.Close()
Dim responseReader As New StreamReader(req.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
Dim fileName As String = responseData
Dim doc As New XmlDocument()
doc.LoadXml(fileName)
Dim categories As New List(Of String)()
Dim nList As XmlNodeList = doc.SelectNodes("/ArrayOfString/string")
For Each node As XmlNode In nList
categories.Add(node.ToString())
Next
我得到的nList为0计数。 下面是我从Web服务获取的xml数据。
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<string>Test1</string>
<string>Test2</string>
<string>Test3</string>
<string>Test4</string>
<string>Test5</string>
<string>Test7</string>
</ArrayOfString>
答案 0 :(得分:0)
这是因为xml具有默认命名空间(xmlns="http://tempuri.org/"
),因此您需要在XPath
查询中使用前缀并使用XmlNamespaceManager
来定义前缀:
.....
Dim namespaceManager As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
namespaceManager.AddNamespace("d", "http://tempuri.org/")
Dim nList As XmlNodeList = doc.SelectNodes("/d:ArrayOfString/d:string", namespaceManager)
......
在XPath查询中未提供前缀时,它将被视为没有命名空间的元素。在XML中,当文件声明了默认名称空间时,所有没有前缀的元素都将被视为默认名称空间[Reference]。