每个 XML 文档可能在最顶部位置有一个声明节点。声明节点提供有关 xml 文档的信息:
<?xml version="1.0" encoding="utf-8"?>
在声明节点之后的 xml 文档中必须存在根节点。在您的情况下,根节点名为“Form_Layout”。
<Form_Layout>
System.Xml 命名空间中可用的类对象可用于读取和操作,然后将数据保存到 xml 文件。您可以使用文件流对象读取 xml 文件的全部内容。您可以修改节点,然后将其保存到新文件或覆盖现有文件。以下代码可用于将 xml 文件加载到 XmlDataDocument 对象中。
Dim xmlDoc As System.Xml.XmlDataDocument = New System.Xml.XmlDataDocument
Dim filepath As String = "C:\Users\mraso\Documents\location.xml"
Dim loadedIn As Boolean = False, readbln As Boolean = False
Dim fstream As System.IO.FileStream = New System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
If fstream IsNot Nothing Then
xmlDoc.Load(fstream)
loadedIn = True
End If
fstream.Close()
fstream.Dispose()
fstream = Nothing
您可以使用 XmlDataDocument 对象的 ChildNodes 属性来读取 xml 文档的声明节点和根节点。你也可以调用每个节点的 ChildNodes 属性来得到它的子节点作为回报。您可以遍历 XmlNodeList 对象中的项目以访问各个节点。使用您的 xml 文件的整个代码如下所示。
Private Sub TestReadingAndSavingXml()
Dim xmlDoc As System.Xml.XmlDataDocument = New System.Xml.XmlDataDocument
Dim filepath As String = "C:\Users\mraso\Documents\location.xml"
Dim loadedIn As Boolean = False, readbln As Boolean = False
Dim fstream As System.IO.FileStream = New System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
If fstream IsNot Nothing Then
xmlDoc.Load(fstream)
loadedIn = True
End If
fstream.Close()
fstream.Dispose()
fstream = Nothing
Dim ndList1 As System.Xml.XmlNodeList = xmlDoc.ChildNodes
If ndList1 IsNot Nothing Then
Dim cnt As Integer = ndList1.Count
For Each nd1 As System.Xml.XmlNode In ndList1
If nd1.Name = "Form_Layout" Then
Dim nd2 As System.Xml.XmlNode = GetChildNode(nd1, "Location")
If nd2 IsNot Nothing Then
Dim nd3 As System.Xml.XmlNode = GetChildNode(nd2, "LocX")
If nd3 IsNot Nothing Then
Dim LocX_value As Integer = nd3.InnerText
Dim s = LocX_value
End If
End If
End If
Next
End If
'Save data to a new xml file
Dim outputXml As String = "C:\Users\mraso\Documents\location2.xml"
xmlDoc.Save(outputXml)
End Sub
Function GetChildNode(ByRef node As System.Xml.XmlNode,
ByVal nodeName As String) As System.Xml.XmlNode
If node IsNot Nothing Then
Dim ndList1 As System.Xml.XmlNodeList = node.ChildNodes
If ndList1 IsNot Nothing Then
For Each nd1 As System.Xml.XmlNode In ndList1
If nd1.Name = nodeName Then
Return nd1
End If
Next
End If
End If
Return Nothing
End Function
上面的代码将读取放在以下 xml 文件中节点“LocX”中的值 100。
<?xml version="1.0" encoding="utf-8"?>
<Form_Layout>
<Location>
<LocX>100</LocX>
<LocY>100</LocY>
</Location>
<Size>
<Width>300</Width>
<Height>300</Height>
</Size>
</Form_Layout>