views:

52

answers:

3

Hello.

I got an Xml file fileOri.xml and there are some lines like

<SubItem name='somename' value='someVal'></SubItem>

and I plan to copy these lines to another file fileDes.xml. Is there a rapidly & easily way?

+2  A: 
  1. Load the XML in a XmlDocument object
  2. Use an XPath like //SubItem to get all SubItem elements
  3. Create a new XmlDocument object
  4. Loop through the nodelist obtained in step 2 and write out the elements.

However, you can also use a stylesheet and then use transform to create the new xml.

Raj
Transforming would be the best solution indeed.
Filburt
A: 

If you just want to copy the whole file, use File.Copy

If you want to copy some of the nodes, open the source using XmlDocument, run zpath query on it using SelectNodes, iterate on resulting node collection and copy each node's .OuterXml to new file.

Alex Reitbort
+2  A: 

Adding to Rajs answer, here's how you can do it using Transform:

The code

XmlTextReader reader = new XmlTextReader("C:\\fileOri.xml");
XmlTextWriter writer = new XmlTextWriter("C:\\fileDes.xml", Encoding.UTF8);
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("C:\\MyStylesheet.xslt");
transform.Transform(reader, writer);

The Stylesheet

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <xsl:template match="/">
        <!-- define the root element for your destination document -->
        <xsl:element name="root">
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>

    <xsl:template match="//SubItem">
        <xsl:copy-of select="." />
    </xsl:template>

</xsl:stylesheet>

Doing it via Transformation gives you the flexibility to change the content you like to copy without touching the executable in the future - just modify the Xslt to your needs.


Hint

Your question suggests that you probably rather want a flat text file with line items for further processing - in that case you can still use Xslt but with text output.

Filburt
@Filburt, Thanks a lot for your tutorial. I will study it.
Nano HE
@Nano, You're welcome. I'll update the sample code to allow for using a Xslt transforming into Xml or CSV file.
Filburt