//向xml文档中指定位置上添加节点 @Test public void add() throws SAXException,IOException,ParserConfigurationException,TransformerException{ //1.创建工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("src/book.xml"); //创建节点 Element pricElement = document.createElement("插入"); pricElement.setTextContent("这里"); //得到参考节点 Element refNodeElement = (Element) document.getElementsByTagName("售价").item(0); //得到要挂的子节点 Element book = (Element) document.getElementsByTagName("书").item(0); //向book节点的指定位置插入 //book.insertBefore(newChild,refChild); book.insertBefore(pricElement,refNodeElement); //把更新后的内存写回到xml TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer tf = tFactory.newTransformer(); tf.transform(new DOMSource(document),new StreamResult(new FileOutputStream("src/book.xml"))); }
<?xml version="1.0" encoding="UTF-8" standalone="no"?><书架> <书> <书名 name="xxxxx">lan</书名> <作者>lan</作者> <售价>100000000000000000元</售价> <二手价>88888888元</二手价></书> <书> <书名 name="yyyyy">lll</书名> <作者>lll</作者> <售价>200000000000000000元</售价> </书> </书架>原文链接:https://www.f2er.com/xml/300417.html