Xmldocument, Difference Between Innerxml and Outerxml

OuterXml - gets the XML markup representing the current node and all its child nodes.

InnerXml - gets the XML markup representing only the child nodes of the current node.

But for XMLDocument does it really matter? (result-wise, well I know it doesn't matter, but logically?).

Example:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
    "<title>Pride And Prejudice</title>" +
    "</book>");

string xmlresponse = doc.OuterXml;
string xmlresponse2 = doc.InnerXml;

In simple words, though both xmlresponse and xmlresponse2 will be the same in the code above. Should I prefer using OuterXml or InnerXml?

3

2 Answers

If you are trying to find why they OuterXml and InnerXml are the same for XmlDocument: look at what XmlDocument represents as node - it is parent of whole Xml tree. But by itself it does not have any visual representation - so "Me"+ "content of children" for it is the same as "content of children".

You can write basic code to walk XmlNode + children and pass XmlDocument to see why it behaves this way:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<?xml version='1.0' ?><root><item>test</item></root>");

Action<XmlNode, string> dump=null;
dump = (root, prefix) => {
  Console.WriteLine("{0}{1} = {2}", prefix, root.Name, root.Value); 
  foreach (XmlNode n in root.ChildNodes)
  {
    dump(n, "  " + prefix);
  }
};

dump(doc,"");

Output shows that XmlDocument there is nothing in XmlDocument itself that have visual representation and the very first node that have text representation is child of it:

#document = 
  xml = version="1.0"
  root = 
    item = 
      #text = test
0

For case where InnerXml equals the OuterXml the following solution will work out if you wanted the InnerXml:

// Create a new Xml doc object with root node as "NewRootNode" and 
// copy the inner content from old doc object using the LastChild.
                    XmlDocument doc = new XmlDocument("FileName");
                    XmlElement newRoot = docNew.CreateElement("NewRootNode");
                    docNew.AppendChild(newRoot);
// The below line solves the InnerXml equals the OuterXml Problem
                    newRoot.InnerXml = oldDoc.LastChild.InnerXml;
                    string xmlText = docNew.OuterXml;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest