我正在将XML文档转换为JSON。
我有一个可能是多个节点的节点。
Json.Net documentation表示强制将节点序列化为数组我应该添加json:array=true
属性。
在我的根节点上,我添加了添加json
命名空间:
writer.WriteAttributeString("xmlns", "json", null, "http://james.newtonking.com/json");
然后在我需要成为数组的元素上添加json:array=true
属性:
writer.WriteAttributeString("Array", "http://james.newtonking.com/json", "true");
XML看起来像预期的那样:
<result xmlns:json="http://james.newtonking.com/json">
<object json:Array="true">
但是JSON看起来像这样:
"result": {
"@xmlns:json": "http://james.newtonking.com/json",
"object": {
"@json:Array": "true",
我做错了什么?
答案 0 :(得分:2)
您的XML命名空间错误。它应该是:
http://james.newtonking.com/projects/json
不
http://james.newtonking.com/json
使用正确的命名空间进行演示:
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter writer = new XmlTextWriter(sw);
string xmlns = "http://james.newtonking.com/projects/json";
writer.Formatting = System.Xml.Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("result");
writer.WriteAttributeString("xmlns", "json", null, xmlns);
writer.WriteStartElement("object");
writer.WriteAttributeString("Array", xmlns, "true");
writer.WriteStartElement("foo");
writer.WriteString("bar");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
string xml = sb.ToString();
Console.WriteLine(xml);
Console.WriteLine();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc,
Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
}
输出:
<?xml version="1.0" encoding="utf-16"?>
<result xmlns:json="http://james.newtonking.com/projects/json">
<object json:Array="true">
<foo>bar</foo>
</object>
</result>
{
"?xml": {
"@version": "1.0",
"@encoding": "utf-16"
},
"result": {
"object": [
{
"foo": "bar"
}
]
}
}