您的位置:首页 > 编程语言 > Java开发

java实现XML增加元素操作简单示例

2017-02-06 12:04 886 查看

本文实例讲述了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:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<书架>
<书>
<书名>Thinking in Java</书名>
<作者>Eric</作者>
<售价>$34</售价>
</书>
</书架>

修改后的XML

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<书架>
<书>
<作者>ZC</作者>
<书名>Thinking in Java</书名>
<作者>Eric</作者>
<售价>$34</售价>
</书>
</书架>

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML:
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代码在线格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

希望本文所述对大家java程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java XML