2014-02-18 25 views
1

我正在将XML文档转换为JSON。json.net没有将xml节点转换为数组

我有一个节点可能是多个节点。

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", 

我在做什么错?

回答

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" 
     } 
    ] 
    } 
}