xml解析

来源:互联网 发布:mac命令行终端工具 编辑:程序博客网 时间:2024/04/29 09:16
一、Dom4j解析xml  遍历与格式输出
package dom4j_xml;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Dom4jTest{
/**
* 遍历xml文档的几种方式
*/
@Test
public void listXML() {
Document document= Dom4jUtil.getDocument("config/book2.xml");
Element root =document.getRootElement(); //得到根结点
List<Element> childList =root.elements(); //得到所有的子元素

for(Element child:childList){
List <Element> eleList =child.elements(); //结点下还有子节点?
//不清楚子结点
for(Element eleNode:eleList){
String eleName =eleNode.getName();
String eleNameVal =eleNode.getText();
System.out.println(eleName+" "+eleNameVal);
}
//清楚子结点
System.out.println(child.elementText("title")+" "+child.elementText("author"));

//不清楚子元素属性
List<Attribute> attrList =root.attributes(); //得到所有子元素的属性
for(Attribute attr:attrList){
String attrName = attr.getName();
String attrVal =attr.getValue();
System.out.println(attrName+" "+attrVal);
}
//清楚子元素的属性
System.out.println("id:"+child.attributeValue("id"));
}
}

/**
* iterator 遍历
*/
@Test
public void testIterator(){
Document document= Dom4jUtil.getDocument("config/book2.xml");
Element root =document.getRootElement(); //得到根结点
Iterator it =root.elementIterator();
while(it.hasNext()){
Element element = (Element) it.next(); //得到子元素

//未知元素名的情况下
Iterator childIt =element.elementIterator();
while(childIt.hasNext()){
Element childEle =(Element) childIt.next();
System.out.println(childEle.getName()+" "+childEle.getText());
}
//已知元素名情况下
System.out.println("title:"+element.elementText("title"));

}
}

/**
* 添加子元素、属性 格式输出
* @throws IOException
*/
@Test
public void testOutput() throws IOException{
Document document =DocumentHelper.createDocument();
Element bookstore =document.addElement("bookstore");

bookstore.addAttribute("id", "store1");
Element book1= bookstore.addElement("book");
book1.addAttribute("id", "Xml book1");
Element title1 =book1.addElement("title");
title1.setText("Hello Xml");
Element author1 = book1.addElement("author");
author1.setText("juze1");
Element price1 =book1.addElement("price");
price1.setText("39.8");

Element book2= bookstore.addElement("book");
book2.addAttribute("id","Xml book2");
Element title2 =book2.addElement("title");
title2.setText("Hello Xml");
Element author2 = book2.addElement("author");
author2.setText("juze1");
Element price2 =book2.addElement("price");
price2.setText("39.8");

Element bookstore2 =bookstore.addElement("store2");
Element book11= bookstore2.addElement("book");
book11.addAttribute("id","Hero book1");
Element title11 =book11.addElement("title");
title11.setText("Hero Xml");
Element author11 = book11.addElement("author");
author11.setText("jane");
Element price11 =book1.addElement("price");
price11.setText("49.8");

Element book22= bookstore.addElement("book");
book22.addAttribute("id","Hero book2");
Element title22 =book22.addElement("title");
title22.setText("Hero Xml");
Element author22 = book22.addElement("author");
author22.setText("kangkang");
Element price22 =book22.addElement("price");
price22.setText("35.8");

OutputFormat format =OutputFormat.createPrettyPrint(); //实例输出格式对象
format.setEncoding("utf-8"); //设置编码
File file = new File("config"+File.separator+"book2.xml"); //构建输出的文件对象
XMLWriter wirter = new XMLWriter(new FileOutputStream(file),format); //生产XMLWiriter对象
wirter.write(document);
}
}

//document 工具类
class Dom4jUtil{
/**
*a static method to get Document object model
*return Document
*/
public static Document getDocument(String fileName) {
SAXReader reader = new SAXReader();
Document document=null;
try {
document = reader.read(new File(fileName));
} catch (DocumentException e) {
e.printStackTrace();
}
return document;
}
}

执行流程:
/**
* 遍历xml文档的几种方式
* 执行流程:dom4j的saxReader.read->document->rootnode -->root.elements(或root.elementIterator)遍历得到所有的子节点。
* 有了根结点就可以得到所属结点的值和属性
* 为结点的听见添加属性和值:
* DocumentHelper.createDocument()-->Document->添加子节点、属性等内容-->OutputFormat.createPrettyPrint()->
* OutputFormat format =OutputFormat.createPrettyPrint(); //实例输出格式对象
format.setEncoding("utf-8"); //设置编码
File file = new File("config"+File.separator+"book2.xml"); //构建输出的文件对象
XMLWriter wirter = new XMLWriter(new FileOutputStream(file),format); //生产XMLWiriter对象
wirter.write(document);
*/


(二)jaxp解析 结点增删改查
package javax_xml_parsers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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.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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**jaxp 解析
* @author jiangz
* @created 2016-05-29
*/
public class JaxpDemo {
public static void main(String[] args) {
//1.创建工厂
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//2.得到dom解析器
try {
DocumentBuilder builder= documentBuilderFactory.newDocumentBuilder();
//3.解析xml文档
try {
Document document = builder.parse("config/book.xml");
} catch (SAXException e) {
} catch (IOException e) {
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}

public static Document getDocument(String filename) throws FileNotFoundException,IOException,Exception{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); //提供的文档创建工厂
DocumentBuilder builder= documentBuilderFactory.newDocumentBuilder(); //得到文档解析器
Document document =builder.parse(filename); //得到一个W3C 文档对象模型的接口
return document;

}
/**
* 读取<book><name>Harry Potter</name><author>J K. Rowling </author><year>2005 </year><price>29.99 </price></book>
* @throws Exception
*/
@Test
public void reader()throws Exception{
Document document =JaxpDemo.getDocument("config/book.xml");
NodeList list =document.getElementsByTagName("book");
Node node =list.item(1);
String content =node.getTextContent();
System.out.println(content);
}

/**得到所有的结点名称
* @throws Exception
*/
@Test
public void readerNodeName()throws Exception{
Document document =JaxpDemo.getDocument("config/book.xml");
Node root =document.getElementsByTagName("bookstore").item(0);
NodeList list =document.getElementsByTagName("author");
list(root);

}

private void list(Node node) {
Node child;
if(node instanceof Element){
System.out.println(node.getNodeName()); //输出结点的名称
NodeList nodeList = node.getChildNodes(); //得到所有的子节点
for(int i=0;i<nodeList.getLength();i++){
child=nodeList.item(i);
list(child);
}
}
}

/**
* 得到结点的属性
* @throws Exception
*/
@Test
public void readerNodeAttr()throws Exception{
Document document =JaxpDemo.getDocument("config/book.xml");
NodeList list = document.getElementsByTagName("book"); //得到标签为book的所有的结点信息
Node node = list.item(0); //得到第一个book标签的结点信息
if(node.hasAttributes()){ //判断有属性没
NamedNodeMap map = node.getAttributes(); //得到第一个book标签所有的属性
for (int i = 0; i < map.getLength(); i++) {
Node nd = map.item(i);
String strName =nd.getNodeName(); //得到单个结点的属性名
String strVal =nd.getNodeValue(); //得到单个结点的属性值
System.out.println("strName:"+strName+" strVal:"+strVal);
}
}
}

/**
* 添加结点num 数量
* @throws Exception
*/
@Test
public void addElement()throws Exception{
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //提供的文档创建工厂
// DocumentBuilder builder= factory.newDocumentBuilder(); //得到文档解析器
// Document document = builder.parse(new FileInputStream("config/book.xml"));
Document document =JaxpDemo.getDocument("config/book.xml");
Element num= document.createElement("num"); //创建结点num
num.setTextContent("10000");
document.getElementsByTagName("book").item(0).appendChild(num); //把创建的结点放到第一本书上
TransformerFactory transformerFactory =TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(); //创建传输转换器
DOMSource source = new DOMSource(document);
FileOutputStream fileOutPutStream = new FileOutputStream(new File("config/book2.xml"));
StreamResult streamResult = new StreamResult(fileOutPutStream);
transformer.transform(source, streamResult); //将更新后的内容写回到文档当中
fileOutPutStream.close();
}

/**
* 向文档中指定位置添加结点
* @throws Exception
*/
@Test
public void addElement2()throws Exception{
Document document =JaxpDemo.getDocument("config/book.xml");
Element num= document.createElement("num"); //创建结点num
num.setTextContent("10000");
Element refNode =(Element) document.getElementsByTagName("year").item(0); //得到参考的结点
Element book =(Element) document.getElementsByTagName("book").item(0); //得到挂载的结点
document.getElementsByTagName("book").item(0).appendChild(num); //把创建的结点放到第一本书上
book.insertBefore(num, refNode); //在挂载结点下的参考结点之前插入新结点
Transformer transformer =TransformerFactory.newInstance().newTransformer();
DOMSource source = new DOMSource(document);
FileOutputStream fileOutPutStream = new FileOutputStream(new File("config/book2.xml"));
StreamResult streamResult = new StreamResult(fileOutPutStream);
transformer.transform(source, streamResult); //将更新后的内容写回到文档当中
fileOutPutStream.close();
}

/**
* 向结点添加属性
* @throws Exception
*/
@Test
public void addElementAttr() throws Exception{
Document document =JaxpDemo.getDocument("config/book2.xml");
Element node = (Element) document.getElementsByTagName("num").item(0); //得到标签为num的第一个结点
node.setAttribute("style", "color='blue'");
Transformer transformer =TransformerFactory.newInstance().newTransformer();
DOMSource source = new DOMSource(document);
FileOutputStream fileOutPutStream = new FileOutputStream(new File("config/book2.xml"));
StreamResult streamResult = new StreamResult(fileOutPutStream);
transformer.transform(source, streamResult); //将更新后的内容写回到文档当中
fileOutPutStream.close();
}

/**
* 更新结点
* @throws Exception
*/
@Test
public void updateElement()throws Exception{
Document document =JaxpDemo.getDocument("config/book2.xml");
Element node = (Element) document.getElementsByTagName("num").item(0); //得到标签为num的第一个结点
node.setTextContent("20000");
node.setAttribute("id", "num_id");
Transformer transformer =TransformerFactory.newInstance().newTransformer();
DOMSource source = new DOMSource(document);
FileOutputStream fileOutPutStream = new FileOutputStream(new File("config/book2.xml"));
StreamResult streamResult = new StreamResult(fileOutPutStream);
transformer.transform(source, streamResult); //将更新后的内容写回到文档当中
fileOutPutStream.close();
}
/**
* 删除节点
* @throws Exception
*/
@Test
public void deleteElement()throws Exception{
Document document =JaxpDemo.getDocument("config/book2.xml");
Element node = (Element) document.getElementsByTagName("num").item(0); //得到标签为num的第一个结点
node.getParentNode().removeChild(node); //删除该结点
Transformer transformer =TransformerFactory.newInstance().newTransformer();
DOMSource source = new DOMSource(document);
FileOutputStream fileOutPutStream = new FileOutputStream(new File("config/book2.xml"));
StreamResult streamResult = new StreamResult(fileOutPutStream);
transformer.transform(source, streamResult); //将更新后的内容写回到文档当中
fileOutPutStream.close();
}
}
0 0
原创粉丝点击