转换xml以使CDATA围绕文本的最佳方法(在java中) [英] Best way to convert xml to have CDATA around text (in java)

查看:777
本文介绍了转换xml以使CDATA围绕文本的最佳方法(在java中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的要求,我需要取一些xml并重新编写它,以便文本节点包装在CDATA中(这适用于不允许正常转义的客户端)。

I have a weird requirement where I need to take some xml and re-write it so that the text nodes are wrapped in CDATA (this is for a client that won't allow normal escaping).

似乎任何普通的XML库dom4j,jdom,java xml都没有内置的支持。有任何想法吗?我可以使用XSLT吗?

It doesn't seem like any of the normal XML libraries dom4j, jdom, java xml, have any built in support for this. Any ideas? Can I use XSLT for this?

我不是很清楚。以下是我要开始的内容:

I wasn't very clear. Here is what I'll start with:

<foo>This has an &amp; escaped value</foo>

我需要做的是将其转换为:

What I need to do is convert this to:

<foo><![CDATA[This has an & escaped value]]></foo>

-Dave

推荐答案

你可以使用XSLT来实现这一点,只要a)你需要输出的所有文本都在元素中,b)你只关心文本节点,c)你知道所有元素的名字包含文本,以及d)可以将所有这些输出元素中的任何文本作为CDATA发出。如果所有这些情况都是真的,那么您可以编写一个标识转换并将此元素添加到它:

You can use XSLT to accomplish this, as long as a) all of the text you need to output is in elements, b) you only care about text nodes, c) you know the names of all the elements that contain text, and d) it's okay to emit any text in all of those output elements as CDATA. If all of those cases are true, then you could write an identity transform and add this element to it:

<xsl:output method="xml" cdata-section-elements="elm1 elm2 elm3..."/>

参见关于这个主题的W3C XSLT推荐

这篇关于转换xml以使CDATA围绕文本的最佳方法(在java中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆