17

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都是相同的。我应该更喜欢使用OuterXmlorInnerXml吗?

4

2 回答 2

19

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

您可以编写基本代码来遍历 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
于 2012-09-25T16:16:51.637 回答
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;
于 2014-02-26T13:31:46.793 回答