当前位置: 动力学知识库 > 问答 > 编程问答 >

Format XML file in java

问题描述:

I already created an xml, and i was obliged to modify it using PrintWriter Class. (copying line by line the xml file and modify what i need) but i lost my indentation.

i tried this :

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document document = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(

"notes.xml"))));

Transformer xformer = TransformerFactory.newInstance().newTransformer();

xformer.setOutputProperty(OutputKeys.METHOD, "xml");

xformer.setOutputProperty(OutputKeys.INDENT, "yes");

xformer.setOutputProperty("b;http://xml.apache.org/xsltd;indent-amount", "4");

//xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

Source source = new DOMSource(document);

Result result = new StreamResult(new File("notes.xml"));

xformer.transform(source, result);

but this isn't working : having an exception in the third line :

[Fatal Error] :3:6537: XML document structures must start and end within the same entity.

org.xml.sax.SAXParseException; lineNumber: 3; columnNumber: 6537; XML document structures must start and end within the same entity.

at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)

at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:347)

So, Is there a way to format an already created XML file in java ?

分享给朋友:
您可能感兴趣的文章:
随机阅读: