用XML中的CDATA换行文本



我有一个生成XML的模板。类似于:

<items>
    <item th:each="itemEntry: ${rs1}">
        <name th:text="${itemEntry.value['ITEM_NAME']}"></name>
    </item>
</items>

我该怎么做才能将元素名称的文本包装在CDATA中,这样结果就会是:

<items>
    <item>
        <name><![CDATA[My text]]></name>
    </item>
</items>

最后很简单。我不得不创建自己的方言:

public class KovicaDialect extends AbstractDialect implements IExpressionObjectDialect {
    private static final XMLExpressionObjectFactory xmlExpressionObjectFactory = new XMLExpressionObjectFactory();
    public KovicaDialect() {
        super("kovica");
    }
    @Override
    public IExpressionObjectFactory getExpressionObjectFactory() {
        return xmlExpressionObjectFactory;
    }
}

表达式对象工厂如下所示:

public class XMLExpressionObjectFactory implements IExpressionObjectFactory {
    private static final String EXPRESSION_OBJECT_PREFIX = "xml";
    private static final Set<String> EXPRESSION_OBJECT_NAMES = Collections.unmodifiableSet(new HashSet(Arrays.asList(EXPRESSION_OBJECT_PREFIX)));
    @Override
    public Set<String> getAllExpressionObjectNames() {
        return EXPRESSION_OBJECT_NAMES;
    }
    @Override
    public Object buildObject(IExpressionContext context, String expressionObjectName) {
        if (expressionObjectName.equals(EXPRESSION_OBJECT_PREFIX) == true) {
            return new XMLUtils();
        }
        return null;
    }
    @Override
    public boolean isCacheable(String expressionObjectName) {
        return true;
    }
}

和util类:

public class XMLUtils {
    public String cdata(String str) {
        String returnString = null;
        if (str != null) {
            returnString = "<![CDATA[" + str + "]]>";
        }
        return returnString;
    }
}

你必须设置这个方言:

org.thymeleaf.TemplateEngine templateEngine = new org.thymeleaf.TemplateEngine();
templateEngine.addDialect(new KovicaDialect());

然后你可以这样使用它(它必须是th:utext(:

<name th:utext="${#xml.cdata(itemEntry.value['ITEM_NAMESMALL'])}"></name>

最新更新