5

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

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)

NovaCenturion
  • 187
  • 1
  • 3
  • 16

3 Answers3

9

It sounds like you just want:

Node cdata = doc.createCDATASection(text);
parentElement.appendChild(cdata);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • How can i add cdata to xml where root element is SignedContent. If i add cdata like u wrote, it will be looks like `<![CDATA[someparameters]]>`. – NovaCenturion Jun 16 '14 at 10:53
  • 1
    @bakash_erni: It's not clear what you mean. What you've shown in your question is CDATA whose content *is* SignedContent. In other words, you should be taking your SignedContent element, converting that to text, creating a CDATASection from that, and adding it to some other node. You can't have an XML document whose root node is itself CDATA. – Jon Skeet Jun 16 '14 at 10:56
9

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...

Rasheed
  • 991
  • 1
  • 12
  • 18
-5

Use Javas + operator:

"<![CDATA[" + "<SignedContent>someparametres</SignedContent>" + "]]>"
ceving
  • 21,900
  • 13
  • 104
  • 178
  • 8
    *Please* don't start manipulating XML documents using string operations. Recipe for failure. – Jon Skeet Jun 13 '14 at 14:21
  • @JonSkeet CDATA contains just character data. It is nothing more than a string. – ceving Nov 21 '17 at 15:23
  • 1
    Good luck with that if the text you want to represent happens to include `]]>`. I'd expect an XML API to make that error clear immediately, rather than giving you an invalid XML document. Bypassing the XML model and using strings is pretty much *always* a bad idea. – Jon Skeet Nov 21 '17 at 15:25
  • @JonSkeet [CDATA sections cannot nest.](https://www.w3.org/TR/xml/#sec-cdata-sect) – ceving Nov 21 '17 at 15:36
  • 3
    Indeed. So will your approach highlight that problem immediately, or create an invalid doc? The latter, I believe - whereas by using an XML API, you can get validation as you construct the doc, making it easier to find problems. – Jon Skeet Nov 21 '17 at 16:31