How to create an XML file from a XmlReader?

16,843

Solution 1

You need to create an XmlWriter and call its WriteNode method.

For example:

using (conn)
using (SqlCommand dataCmd = new SqlCommand(sqlText, Conn)) {
    dataCmd.CommandTimeout = 60000;

    Conn.Open();
    using (XmlReader dataReader = dataCmd.ExecuteXmlReader())
    using (XmlWriter writer = XmlWriter.Create(File.OpenWrite(...)) {
        writer.WriteNode(dataReader, true);
    }
}

Solution 2

The simplest way would be to pass it into an XmlWriter, using a method such as this:

public void WriteOutXml(XmlReader xmlReader, string fileName)
{
    var writer = XmlWriter.Create(fileName);
    writer.WriteNode(xmlReader, true);
}
Share:
16,843

Related videos on Youtube

Andy
Author by

Andy

here to find and give answers

Updated on December 24, 2020

Comments

  • Andy
    Andy over 3 years

    How do you write an XML file from an System.Xml.XmlReader?

    I thought this would be a simple question but whenever I search I seem to be ending up with reading the file to a reader or writing node by node.

    The XmlReader object conveys xml that was stored in a database and just needs to come out of the database to a file. Is there any easy way to do this?

            SqlCommand dataCmd = new SqlCommand(sqlText, Conn);
            System.Xml.XmlReader dataReader = null;
    
            dataCmd.CommandTimeout = 60000;
    
            Conn.Open();
            dataReader = dataCmd.ExecuteXmlReader();
            dataReader.Read();
    
  • Andy
    Andy over 13 years
    i had one using higher up, but this clean up has made the code even better. thank you.
  • Archlight
    Archlight over 10 years
    For the googlers. The file does not get closed if you don't use var settings = new XmlWriterSettings{CloseOutput = true}; XmlWriter.Create(File.OpenWrite(...),settings)