java将cdata添加到xml字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24204749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:48:50  来源:igfitidea点击:

java adding cdata to xml string

javaxmlcdata

提问by NovaCenturion

I need to add CDATA to xml string for sign it with certificate.

我需要将 CDATA 添加到 xml 字符串以使用证书对其进行签名。

String looks like:

字符串看起来像:

<SignedContent>someparametres</SignedContent>

Result must be like:

结果必须是这样的:

<![CDATA[<SignedContent>someparametres</SignedContent>]]>

How can i do this? Pls help

我怎样才能做到这一点?请帮忙

P.S. Xml string has only one row (removed all tabs, all spaces, BOM)

PS Xml 字符串只有一行(去除了所有制表符、所有空格、BOM)

采纳答案by Jon Skeet

It sounds like you just want:

听起来你只想:

Node cdata = doc.createCDATASection(text);
parentElement.appendChild(cdata);

回答by ceving

Use Javas +operator:

使用 Java+运算符:

"<![CDATA[" + "<SignedContent>someparametres</SignedContent>" + "]]>"

回答by Rasheed

This post may be hold but i feel i should respond, this may help someone else.

这个帖子可能会被搁置,但我觉得我应该回复,这可能会帮助别人。

        JAXBContext context = JAXBContext.newInstance(SignedContent.class);
        Marshaller marshallerObj = context.createMarshaller();
        marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter sw = new StringWriter();
        marshallerObj.marshal(signedContentObj, sw);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setExpandEntityReferences(false);
        Document doc = factory.newDocumentBuilder().newDocument();
        doc.createCDATASection(sw.toString()).getData();

You can play around from here...

你可以从这里玩...