简体   繁体   English

解码xml中的cdata内容

[英]decoding cdata content within xml

A customer has sent us an XML file with CDATA content that is XML encoded ie <![CDATA[some content]]> 一位客户已向我们发送了一个XML文件,其中包含经过XML编码的CDATA内容,即<![CDATA[some content]]>

What is the best way in asp.net to replace the content in the XML file with a decoded version? 在asp.net中用解码版本替换XML文件中内容的最佳方法是什么? (without asking the customer to send us a correct file) (不要求客户向我们发送正确的文件)

thanks 谢谢

This might not be what you are looking for, but it will at least give you a start: 这可能不是您想要的,但至少可以为您提供一个开始:

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);
                    }
                }
            }
        }
    }
}

This assumes that your cdata block is the only child of the current node (as per my test). 假设您的cdata块是当前节点的唯一子节点(根据我的测试)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM