DOM4J实例

package cn.csdn.dom;

import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Dom4jTest {

private static Document doc;
/*转载xml文档 到xml文档的Document对象*/
static{
//创建dom4j解析器对象
SAXReader reader = new SAXReader();
//解析器对象 解析指定的xml文档 返回 Document对象
try {
doc = reader.read(new File("src/book.xml"));
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

@Test
public void root(){
System.out.println(doc);
//怎么获取文档的根结点呢
Element root = doc.getRootElement();
listElements(root);
}
//遍历整个文档的元素节点
private void listElements(Element root) {
System.out.println("元素节点名称:"+root.getName());
Iterator<Node> it = root.elementIterator();
while(it.hasNext()){
Node node = it.next();
listElements((Element) node);
}
}

//查找指定的元素节点
@Test
public void findElement(){
Element root = doc.getRootElement();
Element book = root.element("书");
Element name = book.element("书名");
System.out.println(name.getText());
}


//在指定位置添加节点
@Test
public void addElement() throws Exception{
Element root = doc.getRootElement();
Element book = root.element("书");
Element name = book.element("书名");

Element author = DocumentHelper.createElement("作者");
author.setText("大海");
List<Node> nodes = book.elements();
nodes.add(1, author);




OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter( "src/book.xml" ));
writer.write(doc);
writer.close();


}


//在指定位置删除节点
@Test
public void deleteElement() throws Exception{
Element root = doc.getRootElement();
Element book = root.element("书");
Element name = book.element("书名");
name.remove(name.element("作者"));


OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter( "src/book.xml" ));
writer.write(doc);
writer.close();


}


//遍历某个元素节点的属性
@Test
public void attr(){
Element root = doc.getRootElement();
int count = root.attributeCount();
System.out.println(count);
for(int i=0;i<count;i++){
Attribute attribute = root.attribute(i);
System.out.println(attribute.getName()+"=="+attribute.getValue());
}

}

//删除某个元素节点的属性
@Test
public void delAttr()throws Exception{
Element root = doc.getRootElement();
/*
Attribute xm = root.attribute("xm");

root.remove(xm);*/
/*root.addAttribute("xm", "cccc");*/
Attribute xm = root.attribute("xm");
xm.setText("修改呢");


OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileWriter( "src/book.xml" ));
writer.write(doc);
writer.close();

}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用DOM解析XML的示例代码,假设我们要解析如下的XML文档: ```xml <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="children"> <title lang="en">Harry Potter</title> <author>J.K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore> ``` 解析代码如下: ```java import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; public class DomParserExample { public static void main(String[] args) { try { File inputFile = new File("input.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("book"); System.out.println("----------------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Category : " + eElement.getAttribute("category")); System.out.println("Title : " + eElement.getElementsByTagName("title").item(0).getTextContent()); System.out.println("Author : " + eElement.getElementsByTagName("author").item(0).getTextContent()); System.out.println("Year : " + eElement.getElementsByTagName("year").item(0).getTextContent()); System.out.println("Price : " + eElement.getElementsByTagName("price").item(0).getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } } } ``` 运行以上代码,输出如下: ``` Root element :bookstore ---------------------------- Current Element :book Category : children Title : Harry Potter Author : J.K. Rowling Year : 2005 Price : 29.99 Current Element :book Category : web Title : Learning XML Author : Erik T. Ray Year : 2003 Price : 39.95 ``` 以上代码使用了Java标准库中的DOM解析器,首先通过`DocumentBuilderFactory`和`DocumentBuilder`创建解析器实例,然后使用`parse`方法解析XML文档。接着遍历XML文档中的所有`book`元素,获取元素节点的属性和子节点的文本内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值