Someone recently asked on the Undernet #C# channel for help with inserting a block of XML into an existing XML document. After perusing a couple of MSDN articles here's what I came up with.
The problem
The document in question contained several nodes, and one more similar node needed to be added to the end of the document, just before the closing root tag. It wasn't as simple as creating an element and inserting with with System.Xml.XmlNode.AppendChild(). The XML content to be inserted was an element within an element.
The Solution
What I suggested was creating a document fragment and inserting the new XML into that. Then that fragment could be appended to the original document's root element contents.
Here's the solution I proposed. If you have any comments please let me know by posting a comment below.
using System;
using System.Xml;
namespace XMLSample
{
/// <summary>
/// Where the fun starts.
/// </summary>
class Startup
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
// This is the document that we're starting with
string startingXml = @"<?xml version='1.0'?>
<DECORATING_IDEAS_ROOM>
<WEBIMG>
<IMG NAME='Header' src='/images/DecoratingIdeas/livingroom/hdr_living1.gif'/>
</WEBIMG>
<WEBIMG>
<IMG NAME='SubHeader' src='/images/DecoratingIdeas/livingroom/sub_living.gif'/>
</WEBIMG>
<WEBIMG>
<IMG NAME='Room' src='/images/DecoratingIdeas/livingroom/pic_living1.jpg'/>
</WEBIMG>
</DECORATING_IDEAS_ROOM>
";
// Make an XmlDocument that contains the original XML.
XmlDocument doc = new XmlDocument();
doc.LoadXml(startingXml);
Console.WriteLine("The original XML...");
doc.Save(Console.Out);
Console.WriteLine();
// This is the XML that we want to insert.
string toInsert = @"
<WEBIMG>
<IMG NAME='BuyHeader' src='/images/someotherimage.jpg'/>
</WEBIMG>
";
// Create a document fragment to contain the XML to be inserted.
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
// Set the contents of the document fragment.
docFrag.InnerXml = toInsert;
// Add the children of the document fragment to the
// original document.
doc.DocumentElement.AppendChild(docFrag);
Console.WriteLine();
Console.WriteLine("The modified XML:");
doc.Save(Console.Out);
Console.WriteLine();
}
}
}
Comments