【问题标题】:How to change Key value pairs in JSON to XML attributes instead of nodes如何将 JSON 中的键值对更改为 XML 属性而不是节点
【发布时间】:2019-06-19 16:25:26
【问题描述】:

我正在尝试将普通 JSON 更改为 XML,但我不想将 JSON 的键更改为 XML 节点,而是将它们更改为属性。我尝试了以下代码

XNode node = JsonConvert.DeserializeXNode(kvp.ToString(), "root");

但这给了我每个字段作为节点的 XML。

例如我的 JSON 是:

"ItemDetails": [ { "ItemNo": "0001", "Desc": "Office Supplies", "Note": "", "Units": "20" } ]

我想将其更改为关注。将每个键作为属性而不是 XML 节点

<ItemDetails ItemNo="0001" Desc="Office Supplies" Note="" Units="20"/>

【问题讨论】:

    标签: c# .net json xml


    【解决方案1】:

    使用 Newtonsoft 并非开箱即用。相反,您必须创建包含所有节点的 XML,然后重写它,将所有节点移动到属性,然后删除子节点。

    您可以同时使用XmlDocumentXNode 来做到这一点

    XNode 示例

    string json = @"{
        ""ItemDetails"": [
        {
            ""ItemNo"": ""0001"",
            ""Desc"": ""Office Supplies"",
            ""Note"": """",
            ""Units"": ""20""
        }
        ]}";
    
    XNode node = JsonConvert.DeserializeXNode(json, "root");
    
    // select all ItemDetails
    var itemDetails = node.XPathSelectElements("//ItemDetails");
    
    foreach (XElement item in itemDetails)
    {
        foreach (XNode childNode in item.Nodes().ToList())
        {
            // add attribute to node
            var element = childNode as XElement;
            item.SetAttributeValue(element.Name, element.Value);
    
            // remove the childnode
            element.Remove();
        }
    }
    
    Console.WriteLine(node.Document.ToString());
    

    测试运行:https://dotnetfiddle.net/EVDwHN

    XmlDocument 示例

    string json = @"{
        ""ItemDetails"": [
        {
            ""ItemNo"": ""0001"",
            ""Desc"": ""Office Supplies"",
            ""Note"": """",
            ""Units"": ""20""
        }
        ]}";
    
    // using xmldocument
    XmlDocument doc = JsonConvert.DeserializeXmlNode(json, "root", true);
    
    // select all ItemDetails
    var itemDetails = doc.SelectNodes("//ItemDetails");
    
    foreach (XmlNode item in itemDetails)
    {
        foreach (XmlNode childNode in item.ChildNodes.Cast<XmlNode>().ToList())
        {
            var attribute = doc.CreateAttribute(childNode.Name);
            attribute.Value = childNode.InnerText;
    
            // add attribute to node
            item.Attributes.Append(attribute);
    
            // remove the childnode
            item.RemoveChild(childNode);
        }
    }
    
    Console.WriteLine(doc.InnerXml);
    

    测试运行:https://dotnetfiddle.net/9HtdsU

    【讨论】:

    • 这是我问题的完美答案。那段代码很聪明、干净而且很容易理解。非常感谢埃里克。
    • @PShrestha 很酷,如果它是您正在寻找的东西,请将其标记为答案
    猜你喜欢
    • 2021-12-24
    • 2019-12-01
    • 2023-03-08
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 2019-01-28
    • 2021-12-08
    • 2012-08-07
    相关资源
    最近更新 更多