【问题标题】:add XML node with formatting添加带格式的 XML 节点
【发布时间】:2011-12-27 17:28:12
【问题描述】:

我正在向 XML 文件添加一个节点,但我需要正确格式化它。你能帮忙吗?

        String newFile = System.IO.Path.GetFileName(textBox1.Text);

        //file name
        string filename = @"palette.xml";
        XmlDocument doc = new XmlDocument();
        doc.Load(filename);

        //create node and add value
        XmlNode node = doc.CreateNode(XmlNodeType.Element, "item", null);

        //create title node
        XmlNode nodeTitle = doc.CreateElement("name");
        //add value for it
        nodeTitle.InnerText = @"<![CDATA["+newFile+"]]>";

        //create Url node
        XmlNode nodeUrl = doc.CreateElement("imgfile");
        nodeUrl.InnerText = newFile;

        //add to parent node
        node.AppendChild(nodeTitle);
        node.AppendChild(nodeUrl);

        //add to elements collection
        doc.DocumentElement.AppendChild(node);

        //save back
        doc.Save(filename);

XML 应该是这样的:

  <item>
  <name><![CDATA[panda.gif]]></name>
  <imgfile>panda.gif</imgfile>
  </item>

但看起来是这样的:

  <item>
  <name>&lt;![CDATA[panda.gif]]&gt;</name>
  <imgfile>panda.gif</imgfile>
  </item>

【问题讨论】:

    标签: c# xml formatting


    【解决方案1】:

    有一种方法可以用来包装 cdata。

    XMLNode.AppendChild( XMLDocument.CreateCDataSection( newFile ) );
    

    它 XMLDocument.CreateCDataSection 返回 XmlCDataSection 对象,您可以将其附加到您的节点,它会将您的文件包装在 CDATA 中。

    查看此内容了解更多信息:http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createcdatasection.aspx

    【讨论】:

    • 能否给个更好的解释?
    • 不用担心...好的,您在代码中执行此操作的方式是尝试将 CDATA 直接放入内部文本中。这就是它解析不正确的原因。我上面给你的那一行是使用 XMLDocument 类调用一个名为 CreateCDataSection 的方法来将你的字符串包装在 CDATA 中。
    【解决方案2】:

    CDATA 被认为是一个节点,而不是内部文本

    <item>
      <name>
        <![CDATA[panda.gif]]>
      </name>
    
      <imgfile>panda.gif</imgfile>
    </item>
    

    所以:

    XmlElement nodeTitle = document.CreateElement("name");
    XmlCDataSection CDATA = document.CreateCDataSection("panda.gif");
    nodeTitle.AppendChild(CDATA);
    node.AppendChild(nodeTitle);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      相关资源
      最近更新 更多