2011-09-02 94 views
0

客戶向我們發送了一個XML文件,其CDATA內容是XML編碼的 ,即<![CDATA[some content]]>解碼xml中的cdata內容

asp.net用解碼版本替換XML文件中的內容的最佳方法是什麼? (沒有要求客戶向我們發送正確的文件)

謝謝

+0

我想stackoverflow格式化我的例子,所以它不會讀我想要的方式。 cdata標籤實際上是在我們發送的xml中編碼的。即< ; > ; – andrew

回答

0

這可能不是你在找什麼,但它至少給你一個開始:

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塊是當前節點的唯一孩子(按照我的測試)。