本文实例讲述了java实现XML增加元素操作。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
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:
1
2
3
4
5
6
7
8
|
<? xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> <书架> <书> <书名>Thinking in Java</书名> <作者>Eric</作者> <售价>$34</售价> </书> </书架> |
修改后的XML
1
2
3
4
5
6
7
8
9
|
<? xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> <书架> <书> <作者>ZC</作者> <书名>Thinking in Java</书名> <作者>Eric</作者> <售价>$34</售价> </书> </书架> |
希望本文所述对大家java程序设计有所帮助。