XML(五)dom4j增删改查

book2.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<书架> 
  <书> 
    <书名>JAVA</书名>  
    <作者>XXXXXX</作者>  
    <售价>23333</售价> 
  </书>  
  <书> 
    <书名>ANDROID</书名>  
    <作者>XXXXXX</作者>  
    <售价>23333</售价> 
  </书> 
</书架>


 

增删改查方法:

public class dom4j2 {
	public static void main(String[] args) throws Exception {
		// find();
		// add();
		// update();
		// del();
		// attr();
	}

	private static void attr() throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read("book2.xml");

		Element rootElement = document.getRootElement();

		Element bookEle = rootElement.element("书");
		bookEle.addAttribute("出版社", "xxxxxx");
		// 查询出版社
		String publish = bookEle.attributeValue("出版社");

		System.out.println(publish);

		// 删除出版社
		Attribute attr = bookEle.attribute("出版社");
		attr.getParent().remove(attr);

		XMLWriter writer = new XMLWriter(new FileOutputStream("book2.xml"),
				OutputFormat.createPrettyPrint());
		writer.write(document);
		writer.close();
	}

	private static void del() throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read("book2.xml");

		Element rootElement = document.getRootElement();

		Element price2Ele = rootElement.element("书").element("特价");

		price2Ele.getParent().remove(price2Ele);

		XMLWriter writer = new XMLWriter(new FileOutputStream("book2.xml"),
				OutputFormat.createPrettyPrint());
		writer.write(document);
		writer.close();

	}

	private static void update() throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read("book2.xml");

		Element rootElement = document.getRootElement();
		rootElement.element("书").element("特价").setText("50");

		XMLWriter writer = new XMLWriter(new FileOutputStream("book2.xml"),
				OutputFormat.createPrettyPrint());
		writer.write(document);
		writer.close();
	}

	public static void add() throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read("book2.xml");

		Element rootElement = document.getRootElement();

		// 创建 <特价>结点 设置标签体
		Element price2 = DocumentHelper.createElement("特价");
		price2.setText("23232");
		// 获取父节点 并挂载
		Element bookEle1 = rootElement.element("书");
		bookEle1.add(price2);

		// 将内存中的dom树写到xml文件中
		// 方法1
		// FileWriter fw = new FileWriter("book2.xml");
		// document.write(fw);
		// fw.flush();
		// fw.close();
		// 方法2
		XMLWriter writer = new XMLWriter(new FileOutputStream("book2.xml"),
				OutputFormat.createPrettyPrint());// 格式化xml文件
		writer.write(document);
		writer.close();
	}

	public static void find() throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read("book2.xml");

		Element rootElement = document.getRootElement();

		List<Element> elements = rootElement.elements();
		Element book2Ele = elements.get(1);

		System.out.println(book2Ele.element("书名").getText());
	}
}


 

你可能感兴趣的:(xml,dom4j)