当前位置 : 主页 > 编程语言 > c++ >

xml解析之dom4j

来源:互联网 收集:自由互联 发布时间:2021-07-03
gistfile1.txt package cn.jxau.xml;import java.io.FileOutputStream;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;impo
gistfile1.txt
package cn.jxau.xml;

import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;




 class Demo {
	 @Test
	public  void listXml() throws ParserConfigurationException, SAXException, IOException, TransformerException {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//创建工厂
		DocumentBuilder builder = factory.newDocumentBuilder();//用工厂得到解析器
		Document document = builder.parse("book.xml");//用解析器解析文档得到document
		// list1(document);
		list3(document);
	}
	@Test
	public  void list1(Node node) {
		// TODO Auto-generated method stub
		System.out.println(node.getNodeName());// 得到第一个根节点的名字
		NodeList list = node.getChildNodes();// 得到子节点集合
		for (int i = 0; i < list.getLength(); i++) {
			Node child = list.item(i);
			list1(child);
		}
	}
	@Test
	public  void list2(Document document) throws ParserConfigurationException, SAXException, IOException {

		Node node = document.getElementsByTagName("书名").item(1);
		String value = node.getTextContent();
		System.out.println(value);
	}

	@Test
	public  void list3(Document document) throws ParserConfigurationException, SAXException, IOException {

		Node node = document.getElementsByTagName("售价").item(1);
		Element element = (Element) node;
		String price = element.getAttribute("type");
		System.out.println(price);
	}

	@Test
	public  void list4(Document document) throws ParserConfigurationException, SAXException, IOException, TransformerException {

		//创建要挂的节点
		Element element_price = document.createElement("售价");
		element_price.setTextContent("100");
		//把创建好的节点挂到书节点下
			//获取书节点
		Node book_node = document.getElementsByTagName("shu").item(0);
		book_node.appendChild(element_price);
		//把内存中更新后的对象树重新定回到xml文档中
		TransformerFactory factory = TransformerFactory.newInstance();//得到转换器工厂
		Transformer tf = factory.newTransformer();//得到转换器
		tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("book.xml")));//将document转到文档中
	}
}
网友评论