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
?
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With