1、關於本文數組
本文承接了上一篇博客的內容。在上篇博客中,經過函數WriteJsonToXml將一個JSON格式的文件寫入了一個對應的XML文件中。本文中則給出了函數RecoverJsonFromXml的代碼,能夠將XML恢復成JSON格式的文本。函數
運行本文中代碼的環境與上篇博客相同。spa
待讀取的XML文檔內容以下:.net
<?xml version="1.0" encoding="gb2312"?> <!--這個XML文檔中存儲了一個JSON格式的信息--> <Root> <Name Type="String" Value="Tsybius" /> <Age Type="Integer" Value="23" /> <Sex_is_Male Type="Boolean" Value="True" /> <Partner Type="Object"> <Partner_Name Type="String" Value="Galatea" /> <Partner_Age Type="Integer" Value="21" /> <Partner_Sex_is_Male Type="Boolean" Value="False" /> </Partner> <Achievement Type="Array" Value0="ach1" Value1="ach2" Value2="ach3" /> </Root>
2、函數RecoverJsonFromXmlcode
這兩個函數被聲明在類JsonXmlHelper中orm
''' <summary> ''' 將XML格式的內容存儲到JSON格式的字符串中 ''' </summary> ''' <param name="address">要讀取的XML文件地址</param> ''' <remarks></remarks> Public Shared Function RecoverJsonFromXml(address As String) As String Dim xmlDoc = New XmlDocument xmlDoc.Load(address) Dim xmlRoot As XmlNode = xmlDoc.SelectSingleNode("Root") Dim jtemp As JObject = WriteToJson(xmlRoot) Return JsonConvert.SerializeObject(jtemp, Newtonsoft.Json.Formatting.Indented) End Function ''' <summary> ''' 中XmlNode類型中讀取一個JObject類型數據的信息 ''' </summary> ''' <param name="xNode">XML結點類型數據</param> ''' <returns>JObject類型數據</returns> ''' <remarks></remarks> Private Shared Function WriteToJson(xNode As XmlNode) As JObject Dim jobj As New JObject For Each obj As Object In xNode.ChildNodes If obj.GetType.ToString = "System.Xml.XmlElement" Then '讀取到XML結點 Dim xElmt As XmlElement = obj Select Case xElmt.GetAttribute("Type") Case "String" '字符串型變量 jobj.Add(xElmt.Name, xElmt.GetAttribute("Value")) Case "Integer" '整型變量 jobj.Add(xElmt.Name, Integer.Parse(xElmt.GetAttribute("Value"))) Case "Float" '浮點型變量 jobj.Add(xElmt.Name, Double.Parse(xElmt.GetAttribute("Value"))) Case "Boolean" '布爾型變量 jobj.Add(xElmt.Name, IIf(xElmt.GetAttribute("Value") = "True", New JValue(True), New JValue(False))) Case "Array" 'JSON數組 Dim jarr As JArray = New JArray() For i As Integer = 0 To xElmt.Attributes.Count - 2 jarr.Add(New JValue(xElmt.GetAttribute("Value" & i.ToString))) Next jobj.Add(xElmt.Name, jarr) Case "Object" 'JSON對象 jobj.Add(xElmt.Name, WriteToJson(obj)) End Select ElseIf obj.GetType.ToString = "System.Xml.XmlComment" Then '讀取到註釋 Continue For Else '其餘狀況 Continue For End If Next Return jobj End Function
3、調用示例xml
Main代碼對象
Sub Main() Dim sJson As String = JsonXmlHelper.RecoverJsonFromXml("x.xml") Console.WriteLine(sJson) Console.ReadLine() End Sub
4、運行結果blog
ENDrem