我想使用java更改xml中某些字段的文本内容。我为此使用了setTextContent(),但是xml文件没有得到更新。 这是我的java代码:
public static void main(String argv[]) {
DisclosureTranslation dt=new DisclosureTranslation();
String filepath="E:\\Repository\\17Nov_demo\\file.xml";
dt.getHashmap(filepath);
}
public void getHashmap(String filepath){
try {
DocumentBuilderFactory documentbuilderfactory=DocumentBuilderFactory.newInstance();
DocumentBuilder documentbuilder =documentbuilderfactory.newDocumentBuilder();
Document doc=documentbuilder.parse(filepath);
XPath xPath = XPathFactory.newInstance().newXPath();
Element element=doc.getDocumentElement();
NodeList nodelist=(NodeList)xPath.evaluate("/DOCUMENT/ishobject/ishfields/ishfield[@name='FHPIDISCLOSURELEVEL']",
doc.getDocumentElement(), XPathConstants.NODESET);
System.out.println(nodelist.item(0).getTextContent());
String val=nodelist.item(0).getTextContent();
//String val="111";
HashMap<String, String> hashmap=new HashMap<String,String>();
hashmap.put("47406819852170807613486806879990", "public");
hashmap.put("222"," HP Internal");
String value=hashmap.get(val);
nodelist.item(0).setTextContent(value);
System.out.println(nodelist.item(0).getTextContent());
}
最后一行显示我想要的内容。但它没有反映在xml文件中。我想如何更新我的xml文件?
提前致谢! :)
答案 0 :(得分:0)
从文件路径解析xml后更新元素,使用以下方法将它们更新为同一文件。
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File(filePath));
transformer.transform(source, streamResult);
使用&#34; Transformer API&#34;
也可以将xml保存回文件。