【发布时间】:2017-11-02 11:54:39
【问题描述】:
我正在尝试使用 CSharp 中的 Newtonsoft json 将下面包含 html 代码的 xml 转换为 json,
<Content>
<richtext> <![CDATA[<p> <strong>This is sample richtext content </strong> </p> ]]</richtext>
<htmlcontent><![CDATA[ <p> <strong>This is html content </strong> ]]</p> </htmlcontent>
<others> sample </others>
</Content>
我的 C# 代码是
string xmlContent = @"<Content><richtext><![CDATA[ <p> <strong>This is sample richtext content </strong> </p> ]]></richtext><htmlcontent> <![CDATA[<p> <strong>This is html content </strong> </p> ]]></htmlcontent><others> sample </others></Content>";
doc.LoadXml(xmlContent);
string jsonText = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine("JSON is :" + jsonText);
我的输出是
{
"Content": {
"richtext": {
"#cdata-section": " <p> <strong>This is sample richtext content </strong> </p> "
},
"htmlcontent": {
"#cdata-section": "<p> <strong>This is html content </strong> </p> "
},
"others": " sample "
}
}
我的预期输出是
{
"Content": {
"richtext": "<p> <strong>This is sample richtext content </strong> </p>",
"htmlcontent": "<p> <strong>This is html content </strong> </p>",
"others": " sample "
}
}
有没有办法在 JSON 转换过程中去除 XML 中的#cdata-section 元素。
【问题讨论】:
-
您的 XML 无效。在那个 XML
<p>不是 HTML 中,它是一个 xml 节点p。如果你想将 HTML 嵌入到 XML 中,你需要使用 CData -
感谢 Liam,我验证了在 CDATA 中添加 HTML 内容,但仍然得到输出中不需要的“#cdata-section”节点。你能告诉如何在输出中删除它吗?