一个如何自己做的例子:
public static void addElementToXML(String value){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
Document doc = null;
try {
String filePath = "D:\\Loic_Workspace\\Test2\\res\\test.xml";
db = dbf.newDocumentBuilder();
doc = db.parse(new File(filePath));
NodeList ndListe = doc.getElementsByTagName("b");
Integer newId = Integer.parseInt(ndListe.item(ndListe.getLength()-1).getAttributes().item(0).getTextContent()) + 1;
String newXMLLine ="<b id=\""+newId+"\">"+StringEscapeUtils.escapeXml(value)+"</b>";
Node nodeToImport = db.parse(new InputSource(new StringReader(newXMLLine))).getElementsByTagName("b").item(0);
ndListe.item(ndListe.getLength()-1).getParentNode().appendChild(doc.importNode(nodeToImport, true));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
Writer output = new BufferedWriter(new FileWriter(filePath));
String xmlOutput = result.getWriter().toString();
output.write(xmlOutput);
output.close();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
请注意,我使用了Commons Lang中的 StringEscapeUtils 方法。
XMLManager.addElementToXML("& dqsd apzeze /<>'");
之前的文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>
<b id="1">xxx</b>
<b id="2">yyy</b>
<b id="3">zzz</b>
</a>
之后的文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>
<b id="1">xxx</b>
<b id="2">yyy</b>
<b id="3">zzz</b>
<b id="4">& dqsd apzeze /<>'</b>
</a>