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?
Adding to Rajs answer, here's how you can do it using Transform:
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);
<?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.
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.
- Load the XML in a XmlDocument object
- Use an XPath like //SubItem to get all SubItem elements
- Create a new XmlDocument object
- 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.