Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLDocument, difference between innerxml and outerxml

Tags:

c#

xml

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?

like image 984
InfantPro'Aravind' Avatar asked Sep 25 '12 08:09

InfantPro'Aravind'


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
like image 59
Alexei Levenkov Avatar answered Oct 23 '22 11:10

Alexei Levenkov


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;
like image 30
vCillusion Avatar answered Oct 23 '22 11:10

vCillusion