【问题标题】:How to ignore #cdata-section of HTML content during XML to JSON conversion in C#如何在 C# 中的 XML 到 JSON 转换期间忽略 HTML 内容的#cdata-section
【发布时间】: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 &lt;p&gt; 不是 HTML 中,它是一个 xml 节点 p。如果你想将 HTML 嵌入到 XML 中,你需要使用 CData
  • 感谢 Liam,我验证了在 CDATA 中添加 HTML 内容,但仍然得到输出中不需要的“#cdata-section”节点。你能告诉如何在输出中删除它吗?

标签: c# json xml


【解决方案1】:

从文档中删除 CDATA 节点。将 HTML 粘贴为原始数据 - 插入时会转义标签。

让我们使用 Linq2Xml 代替 XmlDocument。更方便。

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>";
var doc = XElement.Parse(xmlContent);

var cdata = doc.DescendantNodes().OfType<XCData>().ToList();
foreach(var cd in cdata)
{
    cd.Parent.Add(cd.Value);
    cd.Remove();
}

Console.WriteLine(doc);

string jsonText = JsonConvert.SerializeXNode(doc, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(jsonText);

【讨论】:

  • 非常感谢@Alexander Petrov & Liam 的回复,这对我很有帮助。
  • 我在序列化后遇到的一个小问题,如果我的 cdata 包含不同行的内容,它会在输出中引入 \n 字符。你能告诉我如何解决这个问题。
  • @user3113876 - 不要在 cmets 中询问。编辑您的问题或提出新问题。向我们展示不同行的示例内容。
猜你喜欢
  • 1970-01-01
  • 2019-09-19
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
  • 2012-02-06
  • 1970-01-01
相关资源
最近更新 更多