//Test
importorg.w3c.dom.Document;importorg.w3c.dom.NodeList;importorg.xml.sax.SAXException;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.ParserConfigurationException;import javax.xml.transform.*;importjavax.xml.transform.dom.DOMSource;importjavax.xml.transform.stream.StreamResult;import java.io.*;public classTest {/*** 读xml文件
*@paramargs*/
public static voidmain(String[] args) {//创建一个DocumentBuilderFactory对象
DocumentBuilderFactory xDocumentBuilderFactory =DocumentBuilderFactory.newInstance();try{//创建一个DocumentBuilder对象
DocumentBuilder xdocumentBuilder =xDocumentBuilderFactory.newDocumentBuilder();//传入要解析的XML文件
Document xDocument = xdocumentBuilder.parse(new File("D:/config.xml"));//通过标签获得节点集合
NodeList beanList = xDocument.getElementsByTagName("good");
System.out.println("共有" + beanList.getLength() + "个节点");//遍历每一个bean节点
for (int i = 0; i < beanList.getLength(); i++) {//获取其中一个节点
String id = beanList.item(i).getAttributes().item(2).getNodeValue();
String name= beanList.item(i).getAttributes().item(3).getNodeValue();
String price= beanList.item(i).getAttributes().item(4).getNodeValue();
String canSale= beanList.item(i).getAttributes().item(1).getNodeValue();
System.out.println(id+ "-" + name + "-" + price + "-" +canSale);//当i=0,即把第一个good的第index=3的属性值修改为联想电脑
if(i==0){
beanList.item(i).getAttributes().item(3).setNodeValue("联想电脑");
}
}//修改之后写入本地xml
TransformerFactory transformerFactory =TransformerFactory.newInstance();
Transformer transformer=transformerFactory.newTransformer();
DOMSource source= newDOMSource(xDocument);
StreamResult result= new StreamResult(new File("D:/config.xml"));
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.transform(source, result);
System.out.println("XML file updated successfully");
}catch(ParserConfigurationException e) {
e.printStackTrace();
}catch(SAXException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(TransformerConfigurationException e) {
e.printStackTrace();
}catch(TransformerException e) {
e.printStackTrace();
}
}
}