【问题标题】:Extract Inner Nodes from XML string to a JSON string从 XML 字符串中提取内部节点到 JSON 字符串
【发布时间】:2020-09-23 08:38:04
【问题描述】:
string inputxml = "<transaction>
<node1>value1</node1>
<node2>value2</node2>
<node3>value3</node3>
</transaction>"

我想在省略最外层节点后将此 XML 字符串转换为以下格式的 JSON 字符串:

{"node1";"value1","node2":"value2","node3":"value3"}

【问题讨论】:

    标签: c# json xml


    【解决方案1】:

    你可以使用:

    1 - XDocument 构建与 Json 匹配的匿名对象,例如:

    string inputxml = @"<transaction>
                            <node1>value1</node1>
                            <node2>value2</node2>
                            <node3>value3</node3>
                        </transaction>";
    
    var node = XDocument.Parse(inputxml)
        .Descendants("transaction")
        .Select(x => new
        {
            Node1 = x.Element("node1").Value,
            Node2 = x.Element("node2").Value,
            Node3 = x.Element("node3").Value
        }).FirstOrDefault();
    

    2 - Newtonsoft 序列化对象,如:

    string json = JsonConvert.SerializeObject(node);
    

    演示

    Console.WriteLine(json);
    

    结果

    {"Node1":"value1","Node2":"value2","Node3":"value3"}
    

    希望对您有所帮助。

    【讨论】:

    • 打败我!不错的答案。并使用匿名来摆脱“外部元素”。
    【解决方案2】:

    据我了解您的问题,您既没有用于源 XML 也没有用于 JSON 的模型,并且名称将来可能会发生变化,因此我们不应该使用严格的名称。所以我们将尝试动态构建它。注意 - 你需要使用 Newtonsoft.Json nuget pack。

    string inputxml = @"<transaction>
    <node1>value1</node1>
    <node2>value2</node2>
    <node3>value3</node3>
    </transaction>";
    
    XDocument xdoc = XDocument.Parse(inputxml); //parse XML document
    var jprops = xdoc.Root.Elements() // take elements in root of the doc
        .Select(x => (x.Name, x.Value)) // map it to tuples (XName, string)
        .Select(x => new JProperty(x.Name.LocalName, x.Value)); //map it to enumerbale of Json properties
    JObject resultingObj = new JObject(jprops); // construct your json and populate its contents
    Console.WriteLine(resultingObj.ToString()); // Write out - u r awesome
    

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2013-07-22
      • 1970-01-01
      相关资源
      最近更新 更多