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

本文实例讲述了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操作的在线工具供大家参考使用:

在线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程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值