码迷,mamicode.com
首页 > 编程语言 > 详细

java JAXB + STAX(是一种针对XML的流式拉分析API)读取xml

时间:2015-06-13 11:13:34      阅读:346      评论:0      收藏:0      [点我收藏+]

标签:

<dependency>
    <groupId>stax</groupId>
    <artifactId>stax-api</artifactId>
    <version>1.0.1</version>
</dependency>

使用XMLStreamReader和XMLEventReader读取XML文件

 1     <?xml version="1.0" encoding="UTF-8"?>  
 2     <company>  
 3         <depart title="Develop Group">  
 4             <user name="Tom" age="28" gender="male" >Manager</user>  
 5             <user name="Lily" age="26" gender="female" />  
 6         </depart>  
 7         <depart title="Test Group">  
 8             <user name="Frank" age="32" gender="male" >Team Leader</user>  
 9             <user name="Bob" age="45" gender="male" />  
10             <user name="Kate" age="25" gender="female" />  
11         </depart>  
12     </company>  

JAVA代码

  1 package xmlstaxdemo;
  2 
  3 import java.io.FileNotFoundException;
  4 import java.io.FileReader;
  5 import java.util.Iterator;
  6 
  7 import javax.xml.namespace.QName;
  8 import javax.xml.stream.EventFilter;
  9 import javax.xml.stream.StreamFilter;
 10 import javax.xml.stream.XMLEventReader;
 11 import javax.xml.stream.XMLInputFactory;
 12 import javax.xml.stream.XMLStreamConstants;
 13 import javax.xml.stream.XMLStreamException;
 14 import javax.xml.stream.XMLStreamReader;
 15 import javax.xml.stream.events.Attribute;
 16 import javax.xml.stream.events.StartElement;
 17 import javax.xml.stream.events.XMLEvent;
 18 
 19 /**
 20  * STAX
 21  *
 22  */
 23 public class App {
 24     // 获得Stream解析器(指针读取器对象)
 25     public static XMLStreamReader getStreamReader() {
 26         XMLStreamReader reader = null;
 27         String xmlFile = App.class.getResource("/").getFile() + "users.xml";
 28         XMLInputFactory factory = XMLInputFactory.newInstance();
 29         try {
 30             reader = factory.createXMLStreamReader(new FileReader(xmlFile));
 31         } catch (FileNotFoundException e) {
 32             e.printStackTrace();
 33         } catch (XMLStreamException e) {
 34             e.printStackTrace();
 35         }
 36         return reader;
 37     }
 38 
 39     // 获得Stream解析器(指针读取器对象),过滤器
 40     public static XMLStreamReader getStreamReader(StreamFilter streamFilter) {
 41         // 创建基于迭代器的指针读取器对象
 42         XMLStreamReader filterReader = null;
 43         String xmlFile = App.class.getResource("/").getFile() + "users.xml";
 44         XMLInputFactory factory = XMLInputFactory.newInstance();
 45         try {
 46             XMLStreamReader reader = factory.createXMLStreamReader(new FileReader(xmlFile));
 47             filterReader = factory.createFilteredReader(reader, streamFilter);
 48         } catch (FileNotFoundException e) {
 49             e.printStackTrace();
 50         } catch (XMLStreamException e) {
 51             e.printStackTrace();
 52         }
 53         return filterReader;
 54     }
 55 
 56     // 列出所有用户名称
 57     public static void listNames() {
 58         // 创建基于迭代器的指针读取器对象
 59         XMLStreamReader reader = App.getStreamReader();
 60         // 遍历XML文档
 61         try {
 62             while (reader.hasNext()) {
 63                 int event = reader.next();
 64                 // 如果是元素的开始
 65                 if (event == XMLStreamConstants.START_ELEMENT) {
 66                     // 列出所有用户名称
 67                     if ("user".equalsIgnoreCase(reader.getLocalName())) {
 68                         System.out.println("Name:" + reader.getAttributeValue(null, "name"));
 69                     }
 70                 }
 71             }
 72             reader.close();
 73         } catch (XMLStreamException e) {
 74             e.printStackTrace();
 75         }
 76     }
 77 
 78     public static void listNamesAndAges() {
 79         XMLStreamReader reader = App.getStreamReader();
 80         try {
 81             while (reader.hasNext()) {
 82                 // 跳过所有空白、注释或处理指令,到下一个START_ELEMENT
 83                 int event = reader.nextTag();
 84                 if (event == XMLStreamConstants.START_ELEMENT) {
 85                     if ("user".equalsIgnoreCase(reader.getLocalName())) {
 86                         System.out.println("Name:" + reader.getAttributeValue(null, "name") + ";Age:" + reader.getAttributeValue(null, "age"));
 87                     }
 88                 }
 89             }
 90             reader.close();
 91         } catch (XMLStreamException e) {
 92             e.printStackTrace();
 93         }
 94     }
 95 
 96     // 获得Event解析器(事件读取器对象)
 97     public static XMLEventReader getEventReader() {
 98         XMLEventReader reader = null;
 99         String xmlFile = App.class.getResource("/").getFile() + "users.xml";
100         XMLInputFactory factory = XMLInputFactory.newInstance();
101         try {
102             reader = factory.createXMLEventReader(new FileReader(xmlFile));
103         } catch (FileNotFoundException e) {
104             e.printStackTrace();
105         } catch (XMLStreamException e) {
106             e.printStackTrace();
107         }
108         return reader;
109     }
110 
111     // 获得Event解析器(指针读取器对象),过滤器
112     public static XMLEventReader getStreamReader(EventFilter eventFilter) {
113         // 创建基于迭代器的指针读取器对象
114         XMLEventReader filterReader = null;
115         String xmlFile = App.class.getResource("/").getFile() + "users.xml";
116         XMLInputFactory factory = XMLInputFactory.newInstance();
117         try {
118             XMLEventReader reader = factory.createXMLEventReader(new FileReader(xmlFile));
119             filterReader = factory.createFilteredReader(reader, eventFilter);
120         } catch (FileNotFoundException e) {
121             e.printStackTrace();
122         } catch (XMLStreamException e) {
123             e.printStackTrace();
124         }
125         return filterReader;
126     }
127 
128     @SuppressWarnings("rawtypes")
129     public static void listAllByXMLEventReader() {
130         // 创建基于迭代器的事件读取器对象
131         XMLEventReader reader = App.getEventReader();
132         try {
133             // 遍历XML文档
134             while (reader.hasNext()) {
135                 XMLEvent event = reader.nextEvent();
136                 // 如果事件对象是元素的开始
137                 if (event.isStartElement()) {
138                     // 转换成开始元素事件对象
139                     StartElement start = event.asStartElement();
140                     // 打印元素标签的本地名称
141                     System.out.print(start.getName().getLocalPart());
142                     // 取得所有属性
143                     Iterator attrs = start.getAttributes();
144                     while (attrs.hasNext()) {
145                         // 打印所有属性信息
146                         Attribute attr = (Attribute) attrs.next();
147                         System.out.print(":" + attr.getName().getLocalPart() + "=" + attr.getValue());
148                     }
149                     System.out.println();
150                 }
151             }
152             reader.close();
153         } catch (XMLStreamException e) {
154             e.printStackTrace();
155         }
156     }
157 
158     public static void listUsersByStreamFilter() {
159         XMLStreamReader streamFilterReader = App.getStreamReader(new StreamFilter() {
160             public boolean accept(XMLStreamReader reader) {
161                 try {
162                     while (reader.hasNext()) {
163                         int event = reader.next();
164                         // 只接受元素的开始
165                         if (event == XMLStreamConstants.START_ELEMENT) {
166                             // 只保留user元素
167                             if ("user".equalsIgnoreCase(reader.getLocalName())) {
168                                 return true;
169                             }
170                         }
171                         if (event == XMLStreamConstants.END_DOCUMENT) {
172                             return true;
173                         }
174                     }
175                 } catch (XMLStreamException e) {
176                     e.printStackTrace();
177                 }
178                 return false;
179             }
180         });
181         try {
182             // 列出所有用户的名称
183             System.out.println(streamFilterReader.getLocalName());
184             while (streamFilterReader.hasNext()) {
185                 // 过滤工作已交由过滤器完成,这里不需要再做user的判断了
186                 System.out.println("Name=" + streamFilterReader.getAttributeValue(null, "name"));
187                 if (streamFilterReader.getEventType() != XMLStreamConstants.END_DOCUMENT) {
188                     streamFilterReader.next();
189                 }
190             }
191             streamFilterReader.close();
192         } catch (XMLStreamException e) {
193             e.printStackTrace();
194         }
195     }
196 
197     public static void listUsersByEventFilter() {
198         XMLEventReader eventFilterReader = App.getStreamReader(new EventFilter() {
199             public boolean accept(XMLEvent event) {
200                 // 如果事件对象是元素的开始
201                 if (event.isStartElement()) {
202                     // 转换成开始元素事件对象
203                     StartElement start = event.asStartElement();
204                     // 打印元素标签的本地名称
205                     return "user".equals(start.getName().getLocalPart());
206                 }
207                 return false;
208             }
209         });
210         try {
211             // 列出所有用户的名称
212             while (eventFilterReader.hasNext()) {
213                 XMLEvent event = eventFilterReader.nextEvent();
214                 StartElement start = event.asStartElement();
215                 System.out.println(start.getName().getLocalPart());
216                 // 过滤工作已交由过滤器完成,这里不需要再做user的判断了
217                 System.out.println("Name=" + start.getAttributeByName(new QName("name")).getValue());
218             }
219             eventFilterReader.close();
220         } catch (XMLStreamException e) {
221             e.printStackTrace();
222         }
223     }
224 
225     public static void main(String[] args) {
226         // listNames();
227         // listNamesAndAges();
228         // listAllByXMLEventReader();
229         // listUsersByStreamFilter();
230          listUsersByEventFilter();
231     }
232 }

 转自:http://blog.chinaunix.net/uid-20749563-id-718396.html

 转自:http://zangweiren.iteye.com/blog/647334

java JAXB + STAX(是一种针对XML的流式拉分析API)读取xml

标签:

原文地址:http://www.cnblogs.com/qiyebao/p/4573071.html

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