Question

Possible Duplicate:
How to disable/avoid Ampersand-Escaping in Java-XML?

i need to create something like: ∧(in the xml-file) and the problem is, that the java technique i am using convertes it to ∧ what doesn´t work for me. i need it in the first format. so, the question is, is there a way to escape it in some way or whatever to get it like that: ∧? for the exporting i am using the same method as here: link

Was it helpful?

Solution

Is this what you want?

    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = f.newDocumentBuilder();

    Document d = builder.newDocument();
    Element root = d.createElement("root");
    d.appendChild(root);
    root.setTextContent("this text contains the \u2227 character");

    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.transform(new DOMSource(d), new StreamResult(System.out));

which produces

<?xml version="1.0" encoding="US-ASCII" standalone="no"?>
<root>this text contains the &#8743; character</root>

OTHER TIPS

The way to do this is using &amp;. Typically it works. If it does not work for your please post some code snippets.

I think the issue is that you're trying to encode the XML by hand.

Try:

  • Convert the user input to Java String
  • Let the XML library take care of converting from Java String to XML String

You could try:

Document doc = documentBuilder.newDocument();
Element root= doc.createElement("root");
doc.appendChild(root);

Document newDoc = documentBuilder.parse(new InputSource(new StringReader("<element defaulttext=\"&#8743;\">some text or XML</element>")));

Element newElement = newDoc.getDocumentElement();
Node node = doc.importNode(newElement, true);

root.appendChild(node);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top