我决定使用 XML 文件保存一些应用程序数据。我对 XML 文件很陌生,所以请耐心等待。
我有这样的课):
Public Class config
Public Property name As String
Public Property type As String
Public Property inputsTable As DataTable
Public Property outputsTable As DataTable
Public Sub WriteXML(filePath As String)
Using writer As XmlWriter = XmlWriter.Create(filePath)
writer.WriteStartDocument()
writer.WriteStartElement("config")
writer.WriteElementString("name", Me.name)
writer.WriteElementString("type", Me.type)
Me.inputsTable.WriteXml(writer)
Me.outputstable.WriteXml(writer)
writer.WriteEndElement()
writer.WriteEndDocument()
End Using
End Sub
End Class
WriteXML sub 会生成如下文件:
<?xml version="1.0" encoding="utf-8"?>
<config>
<name>testConfigName</name>
<type>testConfigType</type>
<DocumentElement>
<inputs>
<inputName>testInputName1</inputName>
<inputValue>testInputValue1</inputValue>
</inputs>
<inputs>
<inputName>testInputName2</inputName>
<inputValue>testInputValue2</inputValue>
</inputs>
</DocumentElement>
<DocumentElement>
<outputs>
<outputName>testOutputName1</outputName>
<outputValue>testOutputValue1</outputValue>
</outputs>
</DocumentElement>
</config>
我有几个问题:
XML 文件中“根节点”的用途是什么?在这里,我创建了一个节点“配置”以使我的代码正常工作,但我真的不明白为什么它是必要的。
是否需要 WriteStartDocument/WriteEndDocument?
如何编写子程序将此文件读回我的应用程序?我特别难以把桌子拿出来。我可以使用以下方法获取单个元素:
Using reader As XmlReader = XmlReader.Create(filePath) While reader.Read() Select Case reader.NodeType Case XmlNodeType.Element Select Case reader.Name Case "name" name = reader.ReadElementContentAsString() Case "type" type = reader.ReadElementContentAsString() End Select End Select End While End Using
但我不知道如何(或是否可能)将其与:
inputsTable.ReadXml(reader) outputsTable.ReadXml(reader)
似乎 ReadXml 可能实际上不适用于我正在尝试做的事情(读取特定表),并且适用于更简单的单表 XML 结构,但我无法明确确认。
任何帮助将不胜感激!