搜索互联网找到了不少于700种不同的方式和意见来完成我想要做的事情,我只想知道最简单,最防弹的方式。
考虑以下XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<xmlCommands>
<command>
<core>
<host>foo</host>
</core>
<protectedServers>
<hostName>bar</hostName>
</protectedServers>
<name>DeleteAgent</name>
</command>
</xmlCommands>
我只想提取字符串“bar”,它位于<hostName></hostName>
内
我可以使用简单的字符串函数轻松地完成此操作,但我想使用其中一个.NET XML类/方法。
答案 0 :(得分:1)
您可以使用Linq to XML:
dim xDoc as xdocument = xdocument.parse(myXmlFile)
dim bar = (from y in xDoc.descendant("hostName") _
select y.Value _
).take(1).singleordefault
或传统的XML类:
dim xDoc as new xml.xmldocument()
xDoc.Load(myXmlFile)
dim node as xml.xmlnode = xdoc.selectSingleNode(xPathStringtoNode)
dim bar as string = node.value
答案 1 :(得分:0)
以下是使用XPATH的示例:
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
'N.B. Need to Import System.Xml
Dim xdc As New XmlDocument
xdc.Load("C:\Junk\Junk.XML")
'1. Search for a node at a particular place
Dim strXpath1 As String = "/xmlCommands/command/protectedServers/hostName" 'N.B. case sensitive
Dim xnd1 As XmlNode = xdc.SelectSingleNode(strXpath1)
If xnd1 IsNot Nothing Then
MsgBox(xnd1.FirstChild.Value)
Else
MsgBox(strXpath1 & " not found")
End If
'2. Search for first match in document
Dim strXpath2 As String = "//hostName" 'N.B. case sensitive
Dim xnd2 As XmlNode = xdc.SelectSingleNode(strXpath2)
If xnd2 IsNot Nothing Then
MsgBox(xnd2.FirstChild.Value)
Else
MsgBox(strXpath2 & " not found")
End If
End Sub