XMLDocument,innerxml和outerxml之间的区别

时间:2012-09-25 08:00:53

标签: c# xml

  

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

     

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

但对于XMLDocument这真的很重要吗? (结果方面,我知道这无关紧要,但逻辑上?)。

示例:

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;

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

2 个答案:

答案 0 :(得分:16)

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

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

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,"");

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

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

答案 1 :(得分:1)

对于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;
相关问题