Newtonsoft.Json的JsonConvert可以把xml转为json,但是对于下面的xml,如果需要Tag转换之后是一个数组,
<TagList>
<Tag>
<Type>0</Type>
<ViewId>16843009</ViewId>
<Note>123</Note>
</Tag>
</TagList>
public static string XML2Json(string xmlstr, string nodename)
{
string result = null;
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlstr);
XmlNode node = xmldoc.SelectSingleNode(nodename);
result = Newtonsoft.Json.JsonConvert.SerializeXmlNode(node);
return result;
}
用上面代码转换后,Tag为单个元素,不是数组。
{
"TagList": {
"Tag": {
"Type": "0",
"ViewId": "16843009",
"Note": "123"
}
}
}
需求是将Tag转换为数组。
解决办法:
把Tag节点添加这样的属性描述:xmlns:json=" http://james.newtonking.com/projects/json " json:Array="true"
代码为:
xmlstr = Regex.Replace(xmlstr, "<Tag>" ,
"<Tagxmlns:json=\"http://james.newtonking.com/projects/json\" json:Array=\"true\" >");
然后再进行转换就可以了