使用Json.NET轉換xml成json時,若是xml只有單個節點,但json要求是數組形式[], html
JsonConvert.SerializeXmlNodejson
並不能自動識別數組
示例以下:app
RecordArray要求是數組格式
<root> <Record> </Record> <RecordArray> <a>1</a> <b>2</b> </RecordArray> </root>
轉換後的json不能知足要求spa
{ "root": { "Record": " ", "RecordArray": { "a": "1", "b": "2" } } }
解決辦法xml
查閱資料後發現很簡單htm
xml根節點須要加上 屬性blog
xmlns:json='http://james.newtonking.com/projects/json'string
須要轉換爲數組的節點加上屬性
json:Array='true' class
以下所示
<root xmlns:json='http://james.newtonking.com/projects/json'>
<Record>
</Record>
<RecordArray json:Array='true' >
<a>1</a>
<b>2</b>
</RecordArray>
</root>
轉換後的json能夠知足要求了
{ "root": { "Record": "", "RecordArray": [ { "a": "1", "b": "2" } ] } }
xml添加屬性:
添加屬性的時候,能夠直接在建立XmlElment的時候,經過XmlElement的SetAttribute來爲節點建立屬性,或者是建立
一個XmlAttribute實例:XmlAttribute xmlArr=XmlDocument.CreateAttribute("屬性值"),而後經過XmlNode的
Attributes.append(XmlArribute)來添加
也能夠string字符替換(只適用於沒重複節點的xml)
xmlInfo = xmlInfo.Replace("<RecordArray>", "<RecordArray json:Array='true'>");
參考:
https://www.newtonsoft.com/json/help/html/ConvertXmlToJsonForceArray.htm