将要读取的xml文档:
<?xml version="1.0" encoding="UTF-8"?>
<书架>
<书>
<书名>java开发</书名>
<作者>andrew</作者>
<售价>29.00元</售价>
</书>
<书>
<书名>JAva就业培训</书名>
<作者>andrew</作者>
<售价>29.00元</售价>
</书>
</书架>
1.读取xml中节点的值;
public void readXML() throws Exception{
//1.创建工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//2.得到dom解析器
DocumentBuilder builder = factory.newDocumentBuilder();
//3.解析xml文档,得到代表文档的document
Document document = builder.parse("src/book.xml");
//读文档
NodeList list = document.getElementsByTagName("书名");
Node nameNode = list.item(1);
String bookName = nameNode.getTextContent();
System.out.println(bookName);
}
2.读取xml中所有节点
@Test
public void readAllNodeName() throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("src/book.xml");
//得到根节点
Node rootNode = document.getElementsByTagName("书架").item(0);
listAllNode(rootNode);
}
private void listAllNode(Node rootNode) {
if(rootNode instanceof Element){
System.out.println(rootNode.getNodeName());
}
NodeList childNodes = rootNode.getChildNodes();
for(int i=0; i<childNodes.getLength(); i++){
Node childNode = childNodes.item(i);
listAllNode(childNode);
}
3.向xml中添加节点
//向xml文档中添加节点,《售价》44.00元《/售价》
@Test
public void add() throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("src/book.xml");
//创建节点
Element price = document.createElement("售价");
price.setTextContent("44.00元");
//把节点挂 到第一本书的节点下
Element book = (Element) document.getElementsByTagName("书").item(0);
book.appendChild(price);
//把更新后的内存的数据写回xml中
TransformerFactory tfFactory = TransformerFactory.newInstance();
Transformer tf = tfFactory.newTransformer();
tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("src/book.xml")));
}
|
|