我正在将XML文档转换为JSON。
我有一个节点,可能是多个节点。
Json.Net 文档说要强制将节点序列化为数组,我应该添加 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",
我做错了什么?
你弄错了 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"
}
]
}
}