XMLDocument,innerxml和outerxml之间的区别

OuterXml – 获取表示当前节点及其所有子节点的XML标记。

InnerXml – 获取仅代表当前节点的子节点的XML标记。

但是对于XMLDocument来说真的很重要吗? (结果明智,我知道这没关系,但逻辑上?)。

例:

 XmlDocument doc = new XmlDocument(); doc.LoadXml("" + "Pride And Prejudice" + ""); string xmlresponse = doc.OuterXml; string xmlresponse2 = doc.InnerXml; 

简单来说,虽然xmlresponsexmlresponse2在上面的代码中都是相同的。 我应该更喜欢使用OuterXml还是InnerXml

如果你试图找到为什么他们的OuterXml和InnerXml对于XmlDocument是相同的:看看XmlDocument表示什么作为节点 – 它是整个Xml树的父。 但它本身并没有任何视觉表现 – 所以“我”+“儿童的内容”与“儿童的内容”相同。

您可以编写基本代码来遍历XmlNode + children并传递XmlDocument以查看它的行为方式:

 XmlDocument doc = new XmlDocument(); doc.LoadXml("test"); Action 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,""); 

输出显示XmlDocument在XmlDocument本身中没有任何东西具有可视化表示,并且第一个具有文本表示的节点是它的子节点:

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

对于InnerXml等于OuterXml的情况,如果你想要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;