C#2.0 read and copy Xml file line by line?

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?

Answers


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">
    <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.


  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.


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.


Need Your Help

Retrieve a column from a table by comparing two different columns from different databases, using PHP MySql

php mysql sql sql-server database

SELECT image_name FROM image_uploader.image_base WHERE image_uploader.image_base.image_id != (select image_id from user_seen.{$value}_seen)

JS consecutive form downloads

javascript browser

I am having a problem with downloading some reports. User has the master entity, then selects from the list of details. When user clicks a button, I group details by their master, and send the requ...