SpaceApple
SpaceApple

Reputation: 1327

Xml within an Xml

I basically want to know how to insert a XmlDocument inside another XmlDocument.

The first XmlDocument will have the basic header and footer tags. The second XmlDocument will be the body/data tag which must be inserted into the first XmlDocument.

            string tableData = null;
            using(StringWriter sw = new StringWriter())
            {
                rightsTable.WriteXml(sw);

                tableData = sw.ToString();                    
            }

            XmlDocument xmlTable = new XmlDocument();
            xmlTable.LoadXml(tableData);

            StringBuilder build = new StringBuilder();
            using (XmlWriter writer = XmlWriter.Create(build, new XmlWriterSettings { OmitXmlDeclaration = true }))
            {
                writer.WriteStartElement("dataheader");

                //need to insert the xmlTable here somehow

                writer.WriteEndElement();
            }

Is there an easier solution to this?

Upvotes: 0

Views: 133

Answers (4)

Oded
Oded

Reputation: 499002

You will need to write the inner XML files in CDATA sections.

Use writer.WriteCData for such nodes, passing in the inner XML as text.

writer.WriteCData(xmlTable.OuterXml);

Another option (thanks DJQuimby) is to encode the XML to some XML compatible format (say base64) - note that the encoding used must be XML compatible and that some encoding schemes will increase the size of the encoded document (base64 adds ~30%).

Upvotes: 1

L.B
L.B

Reputation: 116118

I am not sure what you are really looking for but this can show how to merge two xml documents (using Linq2xml)

string xml1 =
    @"<xml1>
    <header>header1</header>
    <footer>footer</footer>
    </xml1>";

string xml2 =
    @"<xml2>
    <body>body</body> 
    <data>footer</data>
    </xml2>";

var xdoc1 = XElement.Parse(xml1);
var xdoc2 = XElement.Parse(xml2);

xdoc1.Descendants().First(d => d.Name == "header").AddAfterSelf(xdoc2.Elements());

var newxml = xdoc1.ToString();

OUTPUT

<xml1>
  <header>header1</header>
  <body>body</body>
  <data>footer</data>
  <footer>footer</footer>
</xml1>

Upvotes: 1

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can use this code based on CreateCDataSection method

// Create an XmlCDataSection from your document
var cdata = xmlTable.CreateCDataSection("<test></test>");

XmlElement root = xmlTable.DocumentElement;

// Append the cdata section to your node
root.AppendChild(cdata);

Link : http://msdn.microsoft.com/fr-fr/library/system.xml.xmldocument.createcdatasection.aspx

Upvotes: 1

srini.venigalla
srini.venigalla

Reputation: 5145

Use importNode feature in your document parser.

Upvotes: 1

Related Questions