1

Hi i am generating a xml file using javax.xml parsers able to generate a xml file. But in my attribute value i was getting &quot instead of double quote. How to print double quotes in attribute value. Below is my code

Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("elements");
            doc.appendChild(rootElement);
            rootElement.setAttribute("area", "area");
            rootElement.setAttribute("page", "pagename");

            //element
            Element element = doc.createElement("element");
            rootElement.appendChild(element);
            element.setAttribute("key", "key");
            element.setAttribute("id", "id");
            element.setAttribute("path", "//*[@id="email"]");
            }
                    // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(ApplicationContext.getPath()+File.separator+"test.xml"));

            // Output to console for testing
            // StreamResult result = new StreamResult(System.out);

            transformer.transform(source, result);

Output :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<elements area="area" page="pagename">
<element id="id" key="key" path="//*[@id=&quot;email&quot;]"/>
</elements>

Expected output:
 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <elements area="area" page="pagename">
    <element id="id" key="key" path="//*[@id="email"]"/>
    </elements>

Thanks inadvance

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
user3355101
  • 231
  • 6
  • 15

1 Answers1

2

The output you are trying to produce is not well-formed XML, and no XML parser will accept it. If you want to produce stuff that isn't XML then you can do so, of course, but XML-aware tools will try very hard to prevent it.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • That's the correct answer, or course. Just a note; the `"` XML entity that the XML generator produces will of course be transformed back to a double quote by any XML parser when reading the document. – JB Nizet Jan 09 '16 at 10:19