DOM解析.3

//实现增、删、改
import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;


public class DOMconver {


public static void main(String[] args) {
// TODO 自动生成方法存根
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse(new File("student.xml"));
//添加元素
Element eltstudent=doc.createElement("student");
Element eltname=doc.createElement("name");
Element eltage=doc.createElement("age");

Text textname=doc.createTextNode("王五");
Text textage=doc.createTextNode("23");

eltname.appendChild(textname);
eltage.appendChild(textage);

eltstudent.appendChild(eltname);
eltstudent.appendChild(eltage);

eltstudent.setAttribute("ar", "03");

Element root=doc.getDocumentElement();
root.appendChild(eltstudent);
//删除元素
NodeList nl=doc.getElementsByTagName("student");
root.removeChild(nl.item(0));
//修改元素
Element eltstuchg=(Element)nl.item(0);
Node nodestuchg=eltstuchg.getElementsByTagName("age").item(0);
nodestuchg.getFirstChild().setNodeValue("22");

for(int i=0;i<nl.getLength();i++)
{
Element elt=(Element)nl.item(i);
System.out.println("编号: "+elt.getAttribute("ar"));
Node nodename=(Node)elt.getElementsByTagName("name").item(0);
Node nodeage=(Node)elt.getElementsByTagName("age").item(0);
System.out.println("姓名: "+nodename.getFirstChild().getNodeValue());
System.out.println("年龄:  "+nodeage.getFirstChild().getNodeValue());
System.out.println("----------------");
}

TransformerFactory tff=TransformerFactory.newInstance();
Transformer tf=tff.newTransformer();
tf.setOutputProperty("encoding", "gb2312");
DOMSource domsource=new DOMSource(doc);
StreamResult result=new StreamResult(new File("show.xml"));
tf.transform(domsource, result);

} catch (ParserConfigurationException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (SAXException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (TransformerException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}

}

}
//对应的 XML

<?xml version="1.0" encoding="Gb2312"?>
<students>
<student ar="01">
<name>张三</name>
<age>18</age>
</student>
<student ar="02">
<name>李四</name>
<age>19</age>
</student>
</students>

你可能感兴趣的:(xml)