在同一容器节点

时间:2016-06-06 15:39:46

标签: c# xml visual-studio json.net

我正在使用C#在Visual Studio中开发一个应用程序。该应用从JSON转换为XML。转换后,在某些情况下,我会得到XML这样的内容。

<root>
    <row>
        <id>0001</id>
        <type>donut</type>
        <name>Cake</name>
        <ppu>0.55</ppu>
        <topping>
            <id>5001</id>
            <type>None</type>
        </topping>
        <topping>
            <id>5002</id>
            <type>Glazed</type>
        </topping>
        <topping>
            <id>5005</id>
            <type>Sugar</type>
        </topping>
        <topping>
            <id>5007</id>
            <type>Powdered Sugar</type>
        </topping>
        <topping>
            <id>5006</id>
            <type>Chocolate with Sprinkles</type>
        </topping>
        <topping>
            <id>5003</id>
            <type>Chocolate</type>
        </topping>
        <topping>
            <id>5004</id>
            <type>Maple</type>
        </topping>
    </row>
</root>

正如您所看到的,有几个节点具有相同的名称,我想要输出XML

 <root>
    <row>
        <id>0001</id>
        <type>donut</type>
        <name>Cake</name>
        <ppu>0.55</ppu>
        <toppings>
            <topping>
                <id>5001</id>
                <type>None</type>
            </topping>
            <topping>
                <id>5002</id>
                <type>Glazed</type>
            </topping>
            <topping>
                <id>5005</id>
                <type>Sugar</type>
            </topping>
            <topping>
                <id>5007</id>
                <type>Powdered Sugar</type>
            </topping>
            <topping>
                <id>5006</id>
                <type>Chocolate with Sprinkles</type>
            </topping>
            <topping>
                <id>5003</id>
                <type>Chocolate</type>
            </topping>
            <topping>
                <id>5004</id>
                <type>Maple</type>
            </topping>
        </toppings>
    </row>
</root>

使用C#,如何在一个容器节点下对具有相同名称的节点进行分组?

1 个答案:

答案 0 :(得分:1)

var doc = XDocument.Parse(xml); // or XDocument.Load(filename);

var toppings = doc.Root.Element("row").Elements("topping").ToList();

toppings.Remove();

doc.Root.Element("row").Element("ppu").AddAfterSelf(new XElement("toppings", toppings));
// in the doc we have resulting xml

好的,请尝试每种情况。

var doc = XDocument.Parse(xml); // or XDocument.Load(filename);
traverse(doc.Root);
void traverse(XElement elem)
{
    foreach (var e in elem.Elements())
    {
        traverse(e);
    }

    var groups = elem.Elements().GroupBy(e => e.Name);
    foreach (var g in groups)
    {
        if (g.Count() > 1)
        {
            var sameNodes = g.ToList();
            sameNodes.Remove();
            elem.AddFirst(new XElement(g.Key + "s", sameNodes));
        }
    }
}

此代码不保留元素的顺序。它总是在开头插入一组具有相同名称的节点。