简体   繁体   English

如何从XmlReader创建XML文件?

[英]How to create an XML file from a XmlReader?

How do you write an XML file from an System.Xml.XmlReader? 如何从System.Xml.XmlReader编写XML文件?

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. XmlReader对象传达存储在数据库中的xml,只需要从数据库中传出一个文件即可。 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();

You need to create an XmlWriter and call its WriteNode method . 您需要创建一个XmlWriter并调用其WriteNode方法

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);
    }
}

The simplest way would be to pass it into an XmlWriter, using a method such as this: 最简单的方法是将它传递给XmlWriter,使用如下方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM