[英]how to update XML data from java
我想使用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文件?
提前致謝! :)
通過從文件路徑解析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);
也可以使用“ Transformer API”將xml保存回文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.