[英]decoding cdata content within xml
一位客戶已向我們發送了一個XML文件,其中包含經過XML編碼的CDATA內容,即<![CDATA[some content]]>
在asp.net中用解碼版本替換XML文件中內容的最佳方法是什么? (不要求客戶向我們發送正確的文件)
謝謝
這可能不是您想要的,但至少可以為您提供一個開始:
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塊是當前節點的唯一子節點(根據我的測試)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.