本文实例讲述了java实现XML增加元素操作。分享给大家供大家参考,具体如下:
package Day01;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
public class CRUDDEMO {
/*public void addElement() throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File ("src/Day01/Book.xml"));
Element newEle = doc.createElement("作者");
newEle.setTextContent("ZC");
Node nod = doc.getElementsByTagName("书").item(0);
nod.appendChild(newEle);
Source sour = new DOMSource(doc);
Result result = new StreamResult (new FileOutputStream("src/Day01/Book.xml"));
write (sour, result);
}*/
public void addElement2() throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //建立工厂
DocumentBuilder builder = factory.newDocumentBuilder(); //拿到builder
Document doc = builder.parse(new File ("src/Day01/Book.xml")); //获得document,这是终极目的
Element newEle = doc.createElement("作者");// 创建新元素/标签
newEle.setTextContent("ZC"); //给元素设置内容 ZC作者>
Node nod = doc.getElementsByTagName("书名").item(0); //通过nodelist的item()方法获得具体节点
/**
* 在具体节点插入元素用 节点.insertBefore方法
* 第一个参数是要插入的新节点,第二个是插入的位置
*/
nod.insertBefore(newEle, doc.getElementsByTagName("书名").item(0));
/**
* DOMSource(Node n)
* 注意 element是Node的一个子类,所以可以把doc放入构造函数
*
*
*/
Source sour = new DOMSource(doc);
Result result = new StreamResult (new FileOutputStream("src/Day01/Book.xml"));
write (sour, result);
}
public void write(Source source,Result result) {
TransformerFactory tffactory = TransformerFactory.newInstance();
Transformer tr;
try {
tr = tffactory.newTransformer();
tr.transform(source, result);
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
CRUDDEMO cr = new CRUDDEMO();
cr.addElement2();
}
}
修改前的XML:
Thinking in Java书名>
Eric作者>
$34售价>
书>
书架>
修改后的XML
ZC作者>
Thinking in Java书名>
Eric作者>
$34售价>
书>
书架>
PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:
希望本文所述对大家java程序设计有所帮助。