【问题标题】:json.net not converting xml node to arrayjson.net 没有将 xml 节点转换为数组
【发布时间】:2014-02-18 13:17:32
【问题描述】:

我正在将 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",

我做错了什么?

【问题讨论】:

    标签: c# xml json json.net


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 2021-03-16
      • 2014-02-01
      相关资源
      最近更新 更多