XML解析

我就是我 2024-03-16 21:02 124阅读 0赞

目录

一.DOM

2.XPath方式

3.dom4j

1.引入依赖

2.application.xml

3.BeanDefine.java


一.DOM

studentx.xml

  1. <?xml version="1.0"?>
  2. <students>
  3. <student>
  4. <name>John</name>
  5. <grade>B</grade>
  6. <age>12</age>
  7. </student>
  8. <student>
  9. <name>Mary</name>
  10. <grade>A</grade>
  11. <age>11</age>
  12. </student>
  13. <student>
  14. <name>Simon</name>
  15. <grade>A</grade>
  16. <age>18</age>
  17. </student>
  18. </students>

XMLParser.java

  1. import java.io.File;
  2. import javax.xml.parsers.DocumentBuilder;
  3. import javax.xml.parsers.DocumentBuilderFactory;
  4. import org.w3c.dom.Document;
  5. import org.w3c.dom.Element;
  6. import org.w3c.dom.Node;
  7. import org.w3c.dom.NodeList;
  8. public class XMLParser {
  9. public void getAllUserNames(String fileName) {
  10. try {
  11. //1.获得一个文档解析器工厂:定义工厂API,使应用程序能够从XML文档获取生成DOM对象树的解析器
  12. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  13. //2.获得一个文档解析器:定义从XML文档获取DOM文档实例的API。 使用这个类,应用程序员可以从XML获得一个Document 。
  14. DocumentBuilder db = dbf.newDocumentBuilder();
  15. File file = new File(fileName);
  16. if (file.exists()) {
  17. //3.解析器解析xmL文件,获得一个DOM文档
  18. Document doc = db.parse(file);
  19. //4.通过DOM文档获取根结点元素,并打印
  20. Element docEle = doc.getDocumentElement();
  21. System.out.println("Root element of the document: "+ docEle.getNodeName());
  22. //5.通过DOM文档根据标签名获取所有其对应的结点,并将其存储在NodeList抽象集合中
  23. NodeList studentList = docEle.getElementsByTagName("student");
  24. System.out.println("Total students: " + studentList.getLength());
  25. //6.打印"student"结点下所有的结点信息
  26. if(studentList != null && studentList.getLength() > 0) {
  27. for(int i = 0; i < studentList.getLength(); i++) {
  28. //7.遍历一个"student"结点
  29. Node node = studentList.item(i);
  30. //8.node.getNodeType() == Node.ELEMENT_NODE,表示node结点是一个Element(一组)
  31. if(node.getNodeType() == Node.ELEMENT_NODE) {
  32. System.out.println("=====================");
  33. Element e = (Element) node;
  34. NodeList nodeList = e.getElementsByTagName("name");
  35. System.out.println("Name: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
  36. nodeList = e.getElementsByTagName("grade");
  37. System.out.println("Grade: "+nodeList.item(0).getChildNodes().item(0) .getNodeValue());
  38. nodeList = e.getElementsByTagName("age");
  39. System.out.println("Age: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
  40. }
  41. }
  42. }
  43. }
  44. } catch (Exception e) {
  45. System.out.println(e);
  46. }
  47. }
  48. public static void main(String[] args) {
  49. XMLParser parser = new XMLParser();
  50. parser.getAllUserNames("./src/students.xml");
  51. }
  52. }

a8447a750fd84c6a88eb4f5abca975de.png

2.XPath方式

users.xml

  1. <?xml version="1.0"?>
  2. <users>
  3. <user id="1">
  4. <name>张三</name>
  5. <createTime>2018-10-15</createTime>
  6. <password>123</password>
  7. <phone>10086</phone>
  8. <nickName>阿毛</nickName>
  9. </user>
  10. <user id="2">
  11. <name>李四</name>
  12. <createTime>2018-10-15</createTime>
  13. <password>234</password>
  14. <phone>12306</phone>
  15. <nickName>二狗子</nickName>
  16. </user>
  17. </users>
  18. import java.text.DateFormat;
  19. import java.text.ParseException;
  20. import java.text.SimpleDateFormat;
  21. import java.util.Date;
  22. public class UserEntity {
  23. private Long id;
  24. private String name;
  25. private Date createTime;
  26. private String password;
  27. private String phone;
  28. private String nickName;
  29. static UserEntity buildUserEntity(String id, String name, String createTime, String password, String phone,
  30. String nickName) throws ParseException {
  31. UserEntity user=new UserEntity();
  32. user.id=Long.valueOf(id);
  33. user.name=name;
  34. user.createTime=new SimpleDateFormat("yyyy-MM-dd").parse(createTime);
  35. user.password=password;
  36. user.nickName=nickName;
  37. return user;
  38. }
  39. @Override
  40. public String toString() {
  41. // TODO Auto-generated method stub
  42. return id+"-"+name+"-"+createTime+"-"+password+"-"+nickName;
  43. }
  44. }
  45. import java.io.File;
  46. import java.io.FileReader;
  47. import java.util.ArrayList;
  48. import java.util.Date;
  49. import java.util.List;
  50. import javax.xml.parsers.DocumentBuilder;
  51. import javax.xml.parsers.DocumentBuilderFactory;
  52. import javax.xml.xpath.XPath;
  53. import javax.xml.xpath.XPathConstants;
  54. import javax.xml.xpath.XPathFactory;
  55. import org.w3c.dom.Document;
  56. import org.w3c.dom.Element;
  57. import org.w3c.dom.Node;
  58. import org.w3c.dom.NodeList;
  59. public class XMLParser {
  60. public void getAllUserNames(String fileName) {
  61. try {
  62. //1.获得一个文档解析器工厂:定义工厂API,使应用程序能够从XML文档获取生成DOM对象树的解析器
  63. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  64. //2.获得一个文档解析器:定义从XML文档获取DOM文档实例的API。 使用这个类,应用程序员可以从XML获得一个Document 。
  65. DocumentBuilder builder = dbf.newDocumentBuilder();
  66. File file=new File(fileName);
  67. //3.通过解析器解析xml文件,获得一个文档对象
  68. Document document=builder.parse(file);
  69. //4.获取新的XPathFactory实例
  70. XPathFactory xpathFactory=XPathFactory.newInstance();
  71. //5.一个XPathFactory实例可以用来创建XPath对象
  72. XPath xpath=xpathFactory.newXPath();
  73. //6.xpath根据根结点"users"标签解析document文档
  74. NodeList nodeList=(NodeList) xpath.evaluate("/users/*", document,XPathConstants.NODESET);
  75. //7.获取一个ArrayList实例用来存储UserEntity对象
  76. List<UserEntity> userList=new ArrayList<UserEntity>();
  77. //8.获取所有的user结点
  78. for(int i=1;i<nodeList.getLength()+1;i++) {
  79. String path="/users/user["+i+"]";
  80. String id=(String) xpath.evaluate(path+"/@id", document,XPathConstants.STRING);
  81. String name=(String) xpath.evaluate(path+"/name", document,XPathConstants.STRING);
  82. String createTime=(String) xpath.evaluate(path+"/createTime", document,XPathConstants.STRING);
  83. String password=(String) xpath.evaluate(path+"/password", document,XPathConstants.STRING);
  84. String phone=(String) xpath.evaluate(path+"/phone", document,XPathConstants.STRING);
  85. String nickName=(String) xpath.evaluate(path+"/nickName", document,XPathConstants.STRING);
  86. //调用buildUserEntity()方法构建UserEntity对象
  87. UserEntity userEntity=UserEntity.buildUserEntity(id,name,createTime,password,phone,nickName);
  88. userList.add(userEntity);
  89. }
  90. for(UserEntity user:userList) {
  91. System.out.println(user);
  92. }
  93. }catch(Exception e){
  94. e.getMessage();
  95. }
  96. }
  97. public static void main(String[] args) {
  98. XMLParser parser = new XMLParser();
  99. parser.getAllUserNames("./src/users.xml");
  100. }
  101. }

a78694e645ac47e9b07f7045191f6c9c.png

3.dom4j

1.引入依赖

  1. <!-- dom4j解析xml -->
  2. <dependency>
  3. <groupId>dom4j</groupId>
  4. <artifactId>dom4j</artifactId>
  5. <version>1.6.1</version>
  6. </dependency>

2.application.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans>
  3. <bean id="userDao" class="cn.yiguang.testProject.annotation.UserDaoImpl"></bean>
  4. <bean id="user1Dao" class="cn.yiguang.testProject.annotation.User1DaoImpl"></bean>
  5. <bean id="user2Dao" class="cn.yiguang.testProject.annotation.User2DaoImpl"></bean>
  6. <bean id="userService" class="cn.yiguang.testProject.annotation.UserServiceImpl"></bean>
  7. </beans>

3.BeanDefine.java

  1. public class BeanDefine {
  2. private String id;
  3. private String className;
  4. public BeanDefine(String id, String className) {
  5. this.id = id;
  6. this.className = className;
  7. }
  8. public String getId() {
  9. return id;
  10. }
  11. public void setId(String id) {
  12. this.id = id;
  13. }
  14. public String getClassName() {
  15. return className;
  16. }
  17. public void setClassName(String className) {
  18. this.className = className;
  19. }
  20. @Override
  21. public String toString() {
  22. return "id:"+id+",className:"+className;
  23. }
  24. }

4.测试

  1. import java.util.Iterator;
  2. import org.dom4j.Document;
  3. import org.dom4j.DocumentException;
  4. import org.dom4j.Element;
  5. import org.dom4j.io.SAXReader;
  6. public class Test {
  7. public static void main(String[] args) {
  8. // 读取xml文件,转换成Document结点
  9. Document document = null;
  10. // 创建一个SAXReader解析器
  11. SAXReader saxReader = new SAXReader();
  12. try {
  13. ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  14. document = saxReader.read(classLoader.getResourceAsStream("configAnnotation.xml"));
  15. Element beans = document.getRootElement();
  16. for (Iterator<Element> beansList = beans.elementIterator();beansList.hasNext();) {
  17. Element element = beansList.next();
  18. BeanDefine bean = new BeanDefine(element.attributeValue("id"), element.attributeValue("class"));
  19. System.out.println(bean.toString());
  20. }
  21. }catch (DocumentException e){
  22. System.out.println("解析配置文件出错......");
  23. }
  24. }
  25. }

发表评论

表情:
评论列表 (有 0 条评论,124人围观)

还没有评论,来说两句吧...

相关阅读

    相关 XML

    目录 XML解析方式 一.java中配置文件的三种配置位置以及读取方式 1.读取相同目录下配置文件 2.根目录 3.安全路径 WEB-INF 二.DOM4J 2

    相关 【二】、xml

    > 上一篇中说到封装了HttpClient助手类和Json解析响应数据的封装。这节主要扩展响应数据解析类,封装出一个xml解析的实现类,适应微信第三方服务的接口。 主要实现的

    相关 json、xml

    ![Image 1][] -------------------- > 除了XML和Json,文中还涉及到的一些知识:第三方类库的使用,获取本地文件内容,网站API使用,G