xml解析之----DOM解析(二)

2015-01-27 14:14:21 · 作者: · 浏览: 57
//得到要向哪个节点上挂子节点 Node book = document.getElementsByTagName("书").item(0); //向参考节点前,挂新节点 book.insertBefore(price, document.getElementsByTagName("售价").item(0)); //把内存中更新后对象树,重新定回到xml文档中 TransformerFactory factory = TransformerFactory.newInstance(); Transformer tf = factory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("src/book.xml"))); } //向xml文档添加节点属性 @Test public void test5() throws Exception{ Document document = this.document; //得到要添加属性的节点 Element author = (Element) document.getElementsByTagName("作者").item(0); author.setAttribute("id", "12"); //向节点挂属性 //把内存中更新后对象树,重新定回到xml文档中 TransformerFactory factory = TransformerFactory.newInstance(); Transformer tf = factory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("src/book.xml"))); } //删除xml文档中的售价节点 @Test public void test6() throws Exception{ Document document = this.document; //得到要删除的节点 Node price = document.getElementsByTagName("售价").item(0); //得到要删除的节点的父亲 Node parent = document.getElementsByTagName("书").item(0); parent.removeChild(price); //把内存中更新后对象树,重新定回到xml文档中 TransformerFactory factory = TransformerFactory.newInstance(); Transformer tf = factory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("src/book.xml"))); } //删除2 : 删除售价节点所在的书结点 @Test public void test7() throws Exception{ Document document = this.document; //得到要删除的节点 Node price = document.getElementsByTagName("售价").item(0); price.getParentNode().getParentNode().removeChild(price.getParentNode()); //把内存中更新后对象树,重新定回到xml文档中 TransformerFactory factory = TransformerFactory.newInstance(); Transformer tf = factory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("src/book.xml"))); } @Test public void test8() throws Exception{ Document document = this.document; document.getElementsByTagName("售价").item(1).setTextContent("19元"); //把内存中更新后对象树,重新定回到xml文档中 TransformerFactory factory = TransformerFactory.newInstance(); Transformer tf = factory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("src/book.xml"))); } }