如何将修改数据保存到XML文件中,谢谢了
如何将修改数据保存到XML文件中
public String JSetNodeValue(String strNodeName, String strNewNodeValue) {
m_DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
m_DocumentBuilder = m_DocumentBuilderFactory.newDocumentBuilder();
m_Document = m_DocumentBuilder.parse(new File("C:\\aaa.xml"));
NodeList nodes = m_Document.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
nodes childNodeList = node.getChildNodes();
if (node.getNodeName().equals(strNodeName) == true) {
/////////////////////
//写到这里就无法写下去,如何将修改的数据保存到XML或者给一个思路如何实现.谢谢:)
///////////////////
node.getFirstChild().setNodeValue(strNewNodeValue);
JSaveXML();
}
}
public void JSaveXML() {
Transformer xformer = null;
m_FileOutputStream = new FileOutputStream(m_strXMLFileName);
m_OutputStreamWriter = new OutputStreamWriter(m_FileOutputStream);
Source source = new DOMSource(m_Document);
Result res = new StreamResult(m_OutputStreamWriter);
xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
xformer.transform(source, res);
}
------解决方案-------------------- SAXReader reader=new SAXReader();
Document document=reader.read(new File("xx.xml"));
Element book=(Element) document.getRootElement().elements("elements").get(1);
book.element("element").setText("xoo");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
XMLWriter writer=new XMLWriter(new OutputStreamWriter(new FileOutputStream("xx.xml"), "gb2312"),format);
writer.write(document);
writer.close();