Fla*_*ape 2 c# xml cdata url-encoding
所以,我有一个庞大的XML文件,我想删除所有CDATA部分,并用安全的,HTML编码的文本节点替换CDATA节点内容.
用正则表达式剥离CDATA当然会破坏解析.是否有LINQ或XmlDocument或XmlTextWriter技术将CDATA与编码文本交换?
我还不太关心最终的编码,只是如何用我选择的编码替换这些部分.
原始例子
---
<COLLECTION type="presentation" autoplay="false">
<TITLE><![CDATA[Rights & Responsibilities]]></TITLE>
<ITEM id="2802725d-dbac-e011-bcd6-005056af18ff" presenterGender="male">
<TITLE><![CDATA[Watch the demo]]></TITLE>
<LINK><![CDATA[_assets/2302725d-dbac-e011-bcd6-005056af18ff/presentation/presentation-00000000.mp4]]></LINK>
</ITEM>
</COLLECTION>
---
Run Code Online (Sandbox Code Playgroud)
应该成为
<COLLECTION type="presentation" autoplay="false">
<TITLE>Rights & Responsibilities</TITLE>
<ITEM id="2802725d-dbac-e011-bcd6-005056af18ff" presenterGender="male">
<TITLE>Watch the demo</TITLE>
<LINK>_assets/2302725d-dbac-e011-bcd6-005056af18ff/presentation/presentation-00000000.mp4</LINK>
</ITEM>
</COLLECTION>
Run Code Online (Sandbox Code Playgroud)
我想最终的目标是转向JSON.我试过这个
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath( @"~/somefile.xml"));
string jsonText = JsonConvert.SerializeXmlNode(doc);
Run Code Online (Sandbox Code Playgroud)
但我最终得到了丑陋的节点,即"#cdata-section"键.WAAAAY需要花费很多时间才能重新开发前端以接受这一点.
"COLLECTION":[{"@type":"whitepaper","TITLE":{"#cdata-section":"SUPPORTING DOCUMENTS"}},{"@type":"presentation","@autoplay":"false","TITLE":{"#cdata-section":"Demo Presentation"},"ITEM":{"@id":"2802725d-dbac-e011-bcd6-005056af18ff","@presenterGender":"male","TITLE":{"#cdata-section":"Watch the demo"},"LINK":{"#cdata-section":"_assets/2302725d-dbac-e011-bcd6-005056af18ff/presentation/presentation-00000000.mp4"}
Run Code Online (Sandbox Code Playgroud)
使用只将输入复制到输出的XSLT处理XML - C#代码:
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(@"c:\temp\id.xslt");
transform.Transform(@"c:\temp\cdata.xml", @"c:\temp\clean.xml");
Run Code Online (Sandbox Code Playgroud)
id.xslt:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)