首页 > 解决方案 > How do I remove the parent node without removing its child nodes as well?

问题描述

I have the following XML structure:

<root>
    <list>
        <item1>item 1</item1>
        <item2>item 2</item2>
        <item3>item 3</item3>
        <item4>item 4</item4>
        <generated-items>
            <item5>item 5</item5>
            <item6>item 6</item6>
        </generated-items>
    </list>
    <list>
        <item1>item 1</item1>
        <item2>item 2</item2>
        <item3>item 3</item3>
        <item4>item 4</item4>
        <generated-items>
            <item5>item 5</item5>
            <item6>item 6</item6>
        </generated-items>
    </list>
    <list>
        <item1>item 1</item1>
        <item2>item 2</item2>
        <item3>item 3</item3>
        <item4>item 4</item4>
        <generated-items>
            <item5>item 5</item5>
            <item6>item 6</item6>
        </generated-items>
    </list>
</root>

What I want to do is remove the parent tag of the repeating part of the XML file, which should result in the following outcome:

<root>
    <list>
        <item1>item 1</item1>
        <item2>item 2</item2>
        <item3>item 3</item3>
        <item4>item 4</item4>
        <item5>item 5</item5>
        <item6>item 6</item6>
    </list>
    <list>
        <item1>item 1</item1>
        <item2>item 2</item2>
        <item3>item 3</item3>
        <item4>item 4</item4>
        <item5>item 5</item5>
        <item6>item 6</item6>
    </list>
    <list>
        <item1>item 1</item1>
        <item2>item 2</item2>
        <item3>item 3</item3>
        <item4>item 4</item4>
        <item5>item 5</item5>
        <item6>item 6</item6>
    </list>
</root>

What is the best way to do this? I tried to copy the child nodes and paste them inside the repeating list element to make them part of that section, then removing the generating-items element all together.. Although I'm not sure if this is the most optimal way of doing this, and it gets messy real fast this way.

标签: c#xml

解决方案


The best way is to use XSLT-1.0 to transform your input XML to your desired output XML.
This can be achieved by using XslCompiledTransform.
The following stylesheet (transform.xslt) does the job:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <!-- Identity template --> 
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template> 

    <xsl:template match="generated-items">
        <xsl:copy-of select="*" />
    </xsl:template>

</xsl:stylesheet>

The necessary C# code is identical to the example in the link:

// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("transform.xslt");

// Execute the transform and output the results to a file.
xslt.Transform("input.xml", "output.xml");

Then output.xml contains the data you want.


推荐阅读