简体   繁体   English

简单的XML问题

[英]Simple XML Question

I am creating XML at runtime its schema is like 我在运行时创建XML,其架构就像

<Item>
    <Content>Hi</Content>
</item>

The problem is when I am trying to save some HTML contents to this Tag 问题是当我尝试将一些HTML内容保存到该标签时

<Item>
    <Content><strong>Hi<strong></Content>
</item>

How to resolve this issue 如何解决这个问题

Thanks in advance 提前致谢

The correct answer is to not embed tags in XML. 正确的答案是不要在XML中嵌入标签。 The XML should only define the data, the parser should put it in the right markup eg all Item->Contents in <strong></strong> . XML仅应定义数据,解析器应将其放在正确的标记中,例如<strong></strong>所有Item-> Contents。

The other solution is to escape the tags using XML escapes: &lt; 另一种解决方案是使用XML转义符对标签进行转义: &lt; and &gt; &gt; .

I assume that you have a schema that permits an Item element to contain a Content element and that the Content element can only contain text or CDATA or similar. 我假设您有一个架构,该架构允许Item元素包含Content元素,并且Content元素只能包含text或CDATA或类似内容。 You have two options in that case. 在这种情况下,您有两个选择。

Firstly, you could escape the html somehow. 首先,您可以以某种方式转义html。 Either you could use a CDATA section as Fredrik suggested above. 您可以按照Fredrik上面的建议使用CDATA部分。 Alternatively, you could escape the bracketing as above. 另外,您也可以按照上述方法避免包围。 Both of these solutions would allow you to continue to treat the contents of Content as text. 这两种解决方案都可以使您继续将Content的内容视为文本。 This lets you have a simple content model for your element. 这样就可以为您的元素提供一个简单的内容模型。

Alternatively, you could extend your schema to allow xhtml elements as part of the Content element. 另外,您可以扩展架构以允许xhtml元素作为Content元素的一部分。 I suggested a way to that here . 在这里提出了一种解决方法。 Of course, if your content is html not xhtml this won't work. 当然,如果您的内容是html而不是xhtml,则此方法将无效。

Really, the choice comes to whether or not you want to be able to parse the embedded html as part of your xml or not. 确实,选择取决于您是否希望能够将嵌入式html解析为xml的一部分。 If you want it be text, escape it. 如果您希望将其作为文本,请对其进行转义。 If you want it to be parseable, extend your schema. 如果希望它可解析,请扩展您的架构。

您可以将HTML内容嵌入CDATA部分中:

<Item><![CDATA[  <Content><strong>Hi</strong></Content> ]]></item>

The HTML string needs to be properly escaped before you add it to the xml. 在将HTML字符串添加到xml之前,需要对其进行正确的转义。 If you are using .NET here are some ways to do it. 如果您使用的是.NET,则可以使用以下几种方法

The less than tag (<) must be escaped using &lt; 小于标记(<)必须使用&lt;进行转义。 and same for the > tag (&gt;) 和>标记(&gt;)相同

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

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