modifySex(); //方法调用
//修改标签元素
public static void modifySex() throws Exception {
/*
* 1,创建解析器工厂
* 2,根据解析器工厂,创建解析器
* 3,解析xml 返回document
* 4,得到sex item方法
* 5,修改sex里面的值 , setTextContent
* 6,回写
*/
DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
DocumentBuilder db = df.newDocumentBuilder();
Document dt = db.parse("src/person.xml");
NodeList list = dt.getElementsByTagName("sex");
Node sex = list.item(0);
sex.setTextContent("男0");
//回写xml
TransformerFactory tfy = TransformerFactory.newInstance();
Transformer tr = tfy.newTransformer();
tr.transform(new DOMSource(dt), new StreamResult("src/person.xml"));
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?><person>
<p1>
<name>zhangsan</name>
<age>20</age>
<sex>男0</sex>
</p1>
<p1>
<name>lisi</name>
<age>30</age>
</p1>
</person>