解码xml中的cdata内容

问题描述:

客户向我们发送了一个XML文件,其CDATA内容是XML编码的 ,即<![CDATA[some content]]>解码xml中的cdata内容

asp.net用解码版本替换XML文件中的内容的最佳方法是什么? (没有要求客户向我们发送正确的文件)

谢谢

+0

我想*格式化我的例子,所以它不会读我想要的方式。 cdata标签实际上是在我们发送的xml中编码的。即&lt ; &gt ; – andrew

这可能不是你在找什么,但它至少给你一个开始:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Xml; 
using System.Security; 

namespace CSSandbox 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string oldXml = "<root><child>No CDATA here</child><child><![CDATA[Illegal xml & <> '' bobby tables]]></child><child><child><![CDATA[More CDATA &&&]]></child></child></root>"; 
      Console.WriteLine(oldXml); 
      XmlDocument doc = new XmlDocument(); 
      doc.LoadXml(oldXml); 

      ProcessNodes(doc, doc.ChildNodes); 

      string newXml = doc.OuterXml; 
      Console.WriteLine(newXml); 

      Console.ReadLine(); 
     } 
     static void ProcessNodes(XmlDocument doc, XmlNodeList nodes) 
     { 
      foreach (XmlNode node in nodes) 
      { 
       if (node.HasChildNodes) 
       { 
        ProcessNodes(doc, node.ChildNodes); 
       } 
       else 
       { 
        if (node is XmlCDataSection) 
        { 
         string cdataText = node.InnerText; 
         node.ParentNode.InnerXml = SecurityElement.Escape(cdataText); 
        } 
       } 
      } 
     } 
    } 
} 

这是假设你的cdata块是当前节点的唯一孩子(按照我的测试)。