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

JDK1.5需要添加jar包,1.6以后就不需要了
<dependency> <groupId>stax</groupId> <artifactId>stax-api</artifactId> <version>1.0.1</version> </dependency>
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.12</version>
</dependency>

JAXB:JAXB 的全名是Java ™ Architecture for XML Binding

Classroom.java

 1 public class Classroom {

 2     private int id;

 3     private String name;

 4     private int grade;

 5 

 6     public Classroom() {

 7         super();

 8         // TODO Auto-generated constructor stub

 9     }

10 

11     public Classroom(int id, String name, int grade) {

12         super();

13         this.id = id;

14         this.name = name;

15         this.grade = grade;

16     }

17 

18     public int getId() {

19         return id;

20     }

21 

22     public void setId(int id) {

23         this.id = id;

24     }

25 

26     public String getName() {

27         return name;

28     }

29 

30     public void setName(String name) {

31         this.name = name;

32     }

33 

34     public int getGrade() {

35         return grade;

36     }

37 

38     public void setGrade(int grade) {

39         this.grade = grade;

40     }

41 

42     @Override

43     public String toString() {

44         // TODO Auto-generated method stub

45         return String.format("id:%d, name:%s, grade:%d", this.id, this.name, this.grade);

46     }

47 }

Student.java

 1 @XmlRootElement

 2 public class Student {

 3     public int getId() {

 4         return id;

 5     }

 6 

 7     public void setId(int id) {

 8         this.id = id;

 9     }

10 

11     public String getName() {

12         return name;

13     }

14 

15     public void setName(String name) {

16         this.name = name;

17     }

18 

19     public int getAge() {

20         return age;

21     }

22 

23     public void setAge(int age) {

24         this.age = age;

25     }

26 

27     public Classroom getClassroom() {

28         return classroom;

29     }

30 

31     public void setClassroom(Classroom classroom) {

32         this.classroom = classroom;

33     }

34 

35     private int id;

36     private String name;

37     private int age;

38     private Classroom classroom;

39 

40     public Student() {

41         super();

42         // TODO Auto-generated constructor stub

43     }

44 

45     public Student(int id, String name, int age, Classroom classroom) {

46         super();

47         this.id = id;

48         this.name = name;

49         this.age = age;

50         this.classroom = classroom;

51     }

52 

53     @Override

54     public String toString() {

55         // TODO Auto-generated method stub

56         return String.format("id:%d, name:%s, Classroom=>%s", this.id, this.name, this.classroom.toString());

57     }

58 }

main方法:

 1 public static void main(String[] args) throws JAXBException {

 2         Student student = new Student(1, "大帅哥", 34, new Classroom(1, "计算机", 1));

 3         JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);

 4         Marshaller marshaller = jaxbContext.createMarshaller();

 5         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //格式化输出

 6         marshaller.marshal(student, System.out);

 7         StringWriter stringWriter = new StringWriter();

 8         marshaller.marshal(student, stringWriter);

 9         String xml = stringWriter.toString();

10         Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

11         student = (Student) unmarshaller.unmarshal(new StringReader(xml));

12         System.out.println(student.toString());

13     }

STAX:StAX是Streaming API for XML的缩写,是一种针对XML的流式拉分析API。

使用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 // 获得Stream解析器(指针读取器对象)

  2     public static XMLStreamReader getStreamReader() {

  3         XMLStreamReader reader = null;

  4         String xmlFile = App.class.getResource("/").getFile() + "users.xml";

  5         XMLInputFactory factory = XMLInputFactory.newInstance();

  6         try {

  7             reader = factory.createXMLStreamReader(new FileReader(xmlFile));

  8         } catch (FileNotFoundException e) {

  9             e.printStackTrace();

 10         } catch (XMLStreamException e) {

 11             e.printStackTrace();

 12         }

 13         return reader;

 14     }

 15 

 16     // 获得Stream解析器(指针读取器对象),过滤器

 17     public static XMLStreamReader getStreamReader(StreamFilter streamFilter) {

 18         // 创建基于迭代器的指针读取器对象

 19         XMLStreamReader filterReader = null;

 20         String xmlFile = App.class.getResource("/").getFile() + "users.xml";

 21         XMLInputFactory factory = XMLInputFactory.newInstance();

 22         try {

 23             XMLStreamReader reader = factory.createXMLStreamReader(new FileReader(xmlFile));

 24             filterReader = factory.createFilteredReader(reader, streamFilter);

 25         } catch (FileNotFoundException e) {

 26             e.printStackTrace();

 27         } catch (XMLStreamException e) {

 28             e.printStackTrace();

 29         }

 30         return filterReader;

 31     }

 32 

 33     // 列出所有用户名称

 34     public static void listNames() {

 35         // 创建基于迭代器的指针读取器对象

 36         XMLStreamReader reader = App.getStreamReader();

 37         // 遍历XML文档

 38         try {

 39             while (reader.hasNext()) {

 40                 int event = reader.next();

 41                 // 如果是元素的开始

 42                 if (event == XMLStreamConstants.START_ELEMENT) {

 43                     // 列出所有用户名称

 44                     if ("user".equalsIgnoreCase(reader.getLocalName())) {

 45                         System.out.println("Name:" + reader.getAttributeValue(null, "name"));

 46                     }

 47                 }

 48             }

 49             reader.close();

 50         } catch (XMLStreamException e) {

 51             e.printStackTrace();

 52         }

 53     }

 54 

 55     public static void listNamesAndAges() {

 56         XMLStreamReader reader = App.getStreamReader();

 57         try {

 58             while (reader.hasNext()) {

 59                 // 跳过所有空白、注释或处理指令,到下一个START_ELEMENT

 60                 int event = reader.nextTag();

 61                 if (event == XMLStreamConstants.START_ELEMENT) {

 62                     if ("user".equalsIgnoreCase(reader.getLocalName())) {

 63                         System.out.println("Name:" + reader.getAttributeValue(null, "name") + ";Age:" + reader.getAttributeValue(null, "age"));

 64                     }

 65                 }

 66             }

 67             reader.close();

 68         } catch (XMLStreamException e) {

 69             e.printStackTrace();

 70         }

 71     }

 72 

 73     // 获得Event解析器(事件读取器对象)

 74     public static XMLEventReader getEventReader() {

 75         XMLEventReader reader = null;

 76         String xmlFile = App.class.getResource("/").getFile() + "users.xml";

 77         XMLInputFactory factory = XMLInputFactory.newInstance();

 78         try {

 79             reader = factory.createXMLEventReader(new FileReader(xmlFile));

 80         } catch (FileNotFoundException e) {

 81             e.printStackTrace();

 82         } catch (XMLStreamException e) {

 83             e.printStackTrace();

 84         }

 85         return reader;

 86     }

 87 

 88     // 获得Event解析器(指针读取器对象),过滤器

 89     public static XMLEventReader getEventReader(EventFilter eventFilter) {

 90         // 创建基于迭代器的指针读取器对象

 91         XMLEventReader filterReader = null;

 92         String xmlFile = App.class.getResource("/").getFile() + "users.xml";

 93         XMLInputFactory factory = XMLInputFactory.newInstance();

 94         try {

 95             XMLEventReader reader = factory.createXMLEventReader(new FileReader(xmlFile));

 96             filterReader = factory.createFilteredReader(reader, eventFilter);

 97         } catch (FileNotFoundException e) {

 98             e.printStackTrace();

 99         } catch (XMLStreamException e) {

100             e.printStackTrace();

101         }

102         return filterReader;

103     }

104 

105     @SuppressWarnings("rawtypes")

106     public static void listAllByXMLEventReader() {

107         // 创建基于迭代器的事件读取器对象

108         XMLEventReader reader = App.getEventReader();

109         try {

110             // 遍历XML文档

111             while (reader.hasNext()) {

112                 XMLEvent event = reader.nextEvent();

113                 // 如果事件对象是元素的开始

114                 if (event.isStartElement()) {

115                     // 转换成开始元素事件对象

116                     StartElement start = event.asStartElement();

117                     // 打印元素标签的本地名称

118                     System.out.print(start.getName().getLocalPart());

119                     // 取得所有属性

120                     Iterator attrs = start.getAttributes();

121                     while (attrs.hasNext()) {

122                         // 打印所有属性信息

123                         Attribute attr = (Attribute) attrs.next();

124                         System.out.print(":" + attr.getName().getLocalPart() + "=" + attr.getValue());

125                     }

126                     System.out.println();

127                 }

128             }

129             reader.close();

130         } catch (XMLStreamException e) {

131             e.printStackTrace();

132         }

133     }

134 

135     public static void listUsersByStreamFilter() {

136         XMLStreamReader streamFilterReader = App.getStreamReader(new StreamFilter() {

137             public boolean accept(XMLStreamReader reader) {

138                 try {

139                     while (reader.hasNext()) {

140                         int event = reader.next();

141                         // 只接受元素的开始

142                         if (event == XMLStreamConstants.START_ELEMENT) {

143                             // 只保留user元素

144                             if ("user".equalsIgnoreCase(reader.getLocalName())) {

145                                 return true;

146                             }

147                         }

148                         if (event == XMLStreamConstants.END_DOCUMENT) {

149                             return true;

150                         }

151                     }

152                 } catch (XMLStreamException e) {

153                     e.printStackTrace();

154                 }

155                 return false;

156             }

157         });

158         try {

159             // 列出所有用户的名称

160             System.out.println(streamFilterReader.getLocalName());

161             while (streamFilterReader.hasNext()) {

162                 // 过滤工作已交由过滤器完成,这里不需要再做user的判断了

163                 System.out.println("Name=" + streamFilterReader.getAttributeValue(null, "name"));

164                 if (streamFilterReader.getEventType() != XMLStreamConstants.END_DOCUMENT) {

165                     streamFilterReader.next();

166                 }

167             }

168             streamFilterReader.close();

169         } catch (XMLStreamException e) {

170             e.printStackTrace();

171         }

172     }

173 

174     public static void listUsersByEventFilter() {

175         XMLEventReader eventFilterReader = App.getEventReader(new EventFilter() {

176             public boolean accept(XMLEvent event) {

177                 // 如果事件对象是元素的开始

178                 if (event.isStartElement()) {

179                     // 转换成开始元素事件对象

180                     StartElement start = event.asStartElement();

181                     // 打印元素标签的本地名称

182                     return "user".equals(start.getName().getLocalPart());

183                 }

184                 return false;

185             }

186         });

187         try {

188             // 列出所有用户的名称

189             while (eventFilterReader.hasNext()) {

190                 XMLEvent event = eventFilterReader.nextEvent();

191                 StartElement start = event.asStartElement();

192                 System.out.println(start.getName().getLocalPart());

193                 // 过滤工作已交由过滤器完成,这里不需要再做user的判断了

194                 System.out.println("Name=" + start.getAttributeByName(new QName("name")).getValue());

195             }

196             eventFilterReader.close();

197         } catch (XMLStreamException e) {

198             e.printStackTrace();

199         }

200     }

201 

202     public static void main(String[] args) {

203         // listNames();

204         // listNamesAndAges();

205         // listAllByXMLEventReader();

206         // listUsersByStreamFilter();

207         // listUsersByEventFilter();

208     }

 

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

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

你可能感兴趣的:(读取xml)