I have some procedures which return xml files.
Is it possible to concat many xml files using only streams?
something like this:
XmlWriter writer = XmlWriter.Create(sb,settings)
{
foreach(var cmd in XmlFiles)
{
using (XmlReader r = cmd.ExecuteXmlReader())
{
while (r.Read())
{
string xml = r.ReadOuterXml();
writer.WriteRaw(xml);
}
}
}
}
I need do this without using string because i have to deal with big files.
If you don't want to use strings then why do you use ReadOuterXml
and WriteRaw
? There is a method WriteNode
that consumes an XmlReader
passed in, so doing e.g.
string[] inputFiles = { "XMLFile1.xml", "XMLFile2.xml" };
using (XmlWriter xw = XmlWriter.Create("result.xml"))
{
xw.WriteStartDocument();
xw.WriteStartElement("root");
foreach (string inputFile in inputFiles)
{
using (XmlReader xr = XmlReader.Create(inputFile))
{
xr.MoveToContent();
xw.WriteNode(xr, true);
}
}
xw.WriteEndElement();
xw.WriteEndDocument();
would create a new XML document with a root
element wrapping the contents of the two XML files.
In your code you could therefore use
foreach(var cmd in XmlFiles)
{
using (XmlReader r = cmd.ExecuteXmlReader())
{
r.MoveToContent();
writer.WriteNode(r, false);
}
}
as long as you make sure you output a root element wrapper (or you use an XmlWriter with XmlWriterSettings and ConformanceLevel.Fragment).