我決定使用XML文件保存一些應用程序數據。我對XML文件非常陌生,所以請耐心等待。VB.NET:從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子的結果就像一個文件:
<?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文件中的「根節點」的?在這裏,我爲了讓我的代碼正常工作而創建了一個節點「config」,但我並不真的明白爲什麼它是必要的。
是否需要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結構,但我無法確定。
任何幫助將不勝感激!
而不是另起爐竈,考慮XML品種的系列化:保存/載入(的配置)'整個'列表中的代碼,只需幾行 – Plutonix
將它可以爲你鏈接/舉一個例子嗎?我簡要介紹了序列化,但是我發現其實似乎比XmlReader/XmlWriter更復雜,但我肯定會對重新訪問它感興趣。 – Kevin
[序列化時,類繼承另一個類的列表](http://stackoverflow.com/a/23523553/1070452)標題誤導 – Plutonix