码迷,mamicode.com
首页 > 其他好文 > 详细

xml文档解析

时间:2014-05-17 14:14:00      阅读:310      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

XML文档解主要分为四种解析方式,官方提供的两种分别是:DOM 和 SAX,第三方分别是:JDOM 和 DOM4j

 

测试用的xml文档:

bubuko.com,布布扣
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <user>
 3     <uname type="3">zhangsan</uname>
 4     <uname type="2">王麻子</uname>
 5     <uname>lisi</uname>
 6     <pwd>
 7         123456
 8         <abcd>
 9             aaaaaaa
10             <uname type="3">zhaoliu</uname>
11         </abcd>
12         <uname>wangwu</uname>
13     </pwd>
14 </user>
bubuko.com,布布扣

 

使用DOM解析如下:

bubuko.com,布布扣
 1 package com.xmldemo;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import javax.xml.parsers.DocumentBuilder;
 7 import javax.xml.parsers.DocumentBuilderFactory;
 8 import javax.xml.parsers.ParserConfigurationException;
 9 
10 import org.w3c.dom.Document;
11 import org.w3c.dom.Element;
12 import org.w3c.dom.NodeList;
13 import org.xml.sax.SAXException;
14 
15 public class DomTest {
16 
17     public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
18         //创建解析的工厂类
19         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
20         //创建解析
21         DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
22         //获取user.xml的文件流 并且需要保证 xml放在src的根目录
23         InputStream is = DomTest.class.getClassLoader().getResourceAsStream("user.xml");
24         //创建文档对象模型
25         Document document = documentBuilder.parse(is);
26         //获取指定节点的集合
27         NodeList nodeList = document.getElementsByTagName("uname");
28         //遍历并获取
29         for (int i = 0; i < nodeList.getLength(); i++) {
30             Element element = (Element) nodeList.item(i);
31             System.out.println(element.getTagName() + "----->" + element.getAttribute("type") + "---->" + element.getTextContent());
32         }
33 
34     }
35 }
bubuko.com,布布扣

 以下是SAX方式解析:

bubuko.com,布布扣
 1 package com.xmldemo;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 
 8 import javax.xml.parsers.ParserConfigurationException;
 9 import javax.xml.parsers.SAXParser;
10 import javax.xml.parsers.SAXParserFactory;
11 
12 import org.xml.sax.Attributes;
13 import org.xml.sax.SAXException;
14 import org.xml.sax.helpers.DefaultHandler;
15 
16 public class SaxTest {
17     public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
18         //创建解析器的工厂类
19         SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
20         //创建解析器
21         SAXParser saxParser = saxParserFactory.newSAXParser();
22         //获取xml文件流
23         InputStream is = SaxTest.class.getClassLoader().getResourceAsStream("user.xml");
24         //创建自己的处理类
25         MyHandle myHandle = new MyHandle();
26         //直接进行解析
27         saxParser.parse(is, myHandle);
28 
29         for (int i = 0; i < myHandle.list.size(); i++) {
30             System.out.println("SaxTest.main()" + myHandle.list.get(i));
31         }
32     }
33 }
34 
35 /**
36  * 对XMl处理的方法
37  * @author Bjsxt2013
38  *
39  */
40 class MyHandle extends DefaultHandler {
41 
42     public List<String> list = new ArrayList<String>();
43 
44     private String elementName = null;
45 
46     @Override
47     public void characters(char[] ch, int start, int length) throws SAXException {
48         //System.out.println("MyHandle.characters()" + new String(ch, start, length));
49         if (elementName != null && "uname".equals(elementName)) {
50             //System.out.println(new String(ch, start, length));
51             list.add(new String(ch, start, length));
52         }
53     }
54 
55     @Override
56     public void endElement(String uri, String localName, String qName) throws SAXException {
57         //System.out.println("MyHandle.endElement()" + qName);
58         elementName = null;
59     }
60 
61     @Override
62     public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
63         //System.out.println("MyHandle.startElement()" + qName);
64         elementName = qName;
65     }
66 
67     @Override
68     public void startDocument() throws SAXException {
69         //System.out.println("MyHandle.startDocument()");
70     }
71 
72     @Override
73     public void endDocument() throws SAXException {
74         //System.out.println("MyHandle.endDocument()");
75     }
76 }
bubuko.com,布布扣

 

 

以下是JDom方式解析:

bubuko.com,布布扣
  1 package com.xmldemo;
  2 
  3 import java.io.FileNotFoundException;
  4 import java.io.FileOutputStream;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.util.List;
  8 
  9 import org.jdom.Attribute;
 10 import org.jdom.Document;
 11 import org.jdom.Element;
 12 import org.jdom.JDOMException;
 13 import org.jdom.input.SAXBuilder;
 14 import org.jdom.output.Format;
 15 import org.jdom.output.XMLOutputter;
 16 
 17 /**
 18  * 1.如何动态生成xml文件
 19  * 2.如何解析xml文件
 20  * 3.如何修改xml文件
 21  * 
 22  * 如何快速的解析xml文件
 23  * @author Bjsxt2013
 24  *
 25  */
 26 public class JdomTest {
 27 
 28     public static void main(String[] args) throws Exception {
 29         String filePath = System.getProperty("user.dir") + "\\src\\create.xml";
 30         //System.out.println(filePath);
 31         //createXml(filePath);
 32         parserXml(filePath);
 33     }
 34 
 35     /**
 36      * 解析并修改XMl文件
 37      * @param filePath
 38      * @throws JDOMException
 39      * @throws IOException
 40      */
 41     public static void parserXml(String filePath) throws JDOMException, IOException {
 42         //创建JDom的解析器
 43         SAXBuilder saxBuilder = new SAXBuilder();
 44         //获取XML对象的流
 45         InputStream is = JdomTest.class.getClassLoader().getResourceAsStream("create.xml");
 46         //解析并生成document对象
 47         Document document = saxBuilder.build(is);
 48         //获取根节点
 49         Element rootElement = document.getRootElement();
 50         //修改根节点的属性
 51         rootElement.setAttribute("sno", "9999");
 52         rootElement.setAttribute("type01", "aaaaaaaaaaaaaa");
 53         Attribute type = new Attribute("type", "abcdefg");
 54         rootElement.setAttribute(type);
 55 
 56         //获取指定的子节点
 57         Element stuName = rootElement.getChild("stuName");
 58         Element abcd = stuName.getChild("abcd");
 59         //获取节点对应的值
 60         //System.out.println("JdomTest.parserXml()" + abcd.getText());
 61         abcd.setText("唐僧");
 62         //The attribute already has an existing parent "student"
 63         //abcd.setAttribute(type);
 64 
 65         //获取所有的子节点
 66         List<Element> list = rootElement.getChildren();
 67         for (int i = 0; i < list.size(); i++) {
 68             System.out.println("JdomTest.parserXml()" + list.get(i).getName());
 69         }
 70         //创建新的节点
 71         Element score = new Element("score");
 72         score.setText("99");
 73         rootElement.addContent(score);
 74         //再所有的节点之后设置文本内容  不能直接调用setText方法
 75         //rootElement.setText("abcdefghijklmn");
 76         rootElement.addContent("abcdefghij");
 77         //设置写出的格式
 78         Format format = Format.getPrettyFormat();//格式良好的
 79         //Format format = Format.getCompactFormat();//格式紧凑的
 80         format.setEncoding("utf-8");
 81         //将文档对象模型写出到硬盘
 82         XMLOutputter xmlOutputter = new XMLOutputter(format);
 83         xmlOutputter.output(document, new FileOutputStream(filePath));
 84     }
 85 
 86     /**
 87      * 创建一个XML文件
 88      * @param filePath
 89      * @throws FileNotFoundException
 90      * @throws IOException
 91      */
 92     public static void createXml(String filePath) throws FileNotFoundException, IOException {
 93         //创建学生节点(根节点)
 94         Element rootElement = new Element("student");
 95         //添加属性
 96         rootElement.setAttribute("sno", "201209888");
 97         //创建姓名节点
 98         Element stuName = new Element("stuName");
 99         //给姓名节点设置值
100         stuName.setText("柳岩");
101         //创建年龄节点
102         Element age = new Element("age");
103         age.setText("18");
104         //将节点连起来
105         rootElement.addContent(stuName);
106         rootElement.addContent(age);
107 
108         //创建文档对象模型
109         Document document = new Document(rootElement);
110         //设置写出的格式
111         Format format = Format.getPrettyFormat();//格式良好的
112         //Format format = Format.getCompactFormat();//格式紧凑的
113         format.setEncoding("utf-8");
114         //将文档对象模型写出到硬盘
115         XMLOutputter xmlOutputter = new XMLOutputter(format);
116         xmlOutputter.output(document, new FileOutputStream(filePath));
117     }
118 }
bubuko.com,布布扣

 

 

 

xml文档解析,布布扣,bubuko.com

xml文档解析

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/IT-One/p/3730993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!