I am testing a standard xml parser with code
the xml file is
<? xml version='1.0' encoding='UTF-8'?>
<A></A>
and Java…
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db=null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document doc=null;
try {
doc = (Document) db.parse(filePath);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element a= (Element) doc.getElementsByTagName("A").item(0);
Element b=(Element) doc.createElement("B");
b.setAttribute("id", "12345");
a.appendChild(b);
Transformer transformer=null;
try {
transformer = TransformerFactory.newInstance().newTransformer();
} catch (TransformerConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (TransformerFactoryConfigurationError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
try {
transformer.transform(source, result);
} catch (TransformerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String xml= result.getWriter().toString();
… for some reason the xml var value is always
[#document: null]
though I want to get xml itself 🙁 So I just wondering why it is always null? And How to get inner modified xml to save it lets say to a file?
Works on my machine – the output you say [#docuument: null] is normal for a toString on a Document.