Search code examples
javaxmlexportampersand

exporting the &-sign to xml from java


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


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>