/*
* 1,创建解析器工厂
* 2,创建解析器
* 3,解析xml 返回document
* 4,得到第一个p1
* 5,创建标签 sex createElement
* 6,创建文本 createTextNode
* 7,把文本添加到所创建的标签里appendChild
* 8,把新创建的标签添加到P1后面
* 9,回写xml
*/
public static void addsex() throws Exception {
DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
DocumentBuilder dr = df.newDocumentBuilder();
Document document = dr.parse("src/person.xml");
NodeList list = document.getElementsByTagName("p1");
Node p1 = list.item(0);
//创建标签sex
Element sex1 = document.createElement("sex");
Text text1 = document.createTextNode("女");
sex1.appendChild(text1);//把文本添加到sex标签
p1.appendChild(sex1);
//xml回写
TransformerFactory tfy = TransformerFactory.newInstance();
Transformer tf = tfy.newTransformer();
tf.transform(new DOMSource(document), new StreamResult("src/person.xml"));
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?><person>
<p1>
<name>zhangsan</name>
<age>20</age>
<sex>女</sex> //为新添加的标签
</p1>
<p1>
<name>lisi</name>
<age>30</age>
</p1>
</person>