• 【XML配置文件读取】使用jdom读取XML配置文件信息


    在项目中我们经常需要将配置信息写在配置文件中,而XML配置文件是常用的格式。
    下面将介绍如何通过jdom来读取xml配置文件信息。

    配置文件信息


    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <config>
    3. <base-config>
    4. <stringValue>Hello world</stringValue>
    5. <integerValue>8</integerValue>
    6. <longValue>32768</longValue>
    7. </base-config>
    8. <books>
    9. <book id="111">
    10. <name>Java 编程</name>
    11. <price>33</price>
    12. </book>
    13. <book id="222">
    14. <name>Spring学习指南</name>
    15. <price>55</price>
    16. </book>
    17. </books>
    18. <computers>
    19. <computer type="dell" size="14寸" />
    20. <computer type="thinkpad" size="16寸" />
    21. <computer type="apple" size="22寸" />
    22. </computers>
    23. </config>


    需要的Jar包(MAVEN给出)



    完整的POM文件


    1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    3. <modelVersion>4.0.0</modelVersion>
    4. <groupId>com.ll</groupId>
    5. <artifactId>myThreadStudy</artifactId>
    6. <version>0.0.1-SNAPSHOT</version>
    7. <packaging>jar</packaging>
    8. <name>myThreadStudy</name>
    9. <url>http://maven.apache.org</url>
    10. <properties>
    11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    12. <junitVersion>3.8.1</junitVersion>
    13. <commons-io-Version>2.4</commons-io-Version>
    14. <jaxenVersion>1.1.1</jaxenVersion>
    15. <jdomVersion>1.1</jdomVersion>
    16. <log4jVersion>1.2.17</log4jVersion>
    17. </properties>
    18. <dependencies>
    19. <dependency>
    20. <groupId>junit</groupId>
    21. <artifactId>junit</artifactId>
    22. <version>${junitVersion}</version>
    23. <scope>test</scope>
    24. </dependency>
    25. <dependency>
    26. <groupId>commons-io</groupId>
    27. <artifactId>commons-io</artifactId>
    28. <version>${commons-io-Version}</version>
    29. </dependency>
    30. <dependency>
    31. <groupId>org.jdom</groupId>
    32. <artifactId>jdom</artifactId>
    33. <version>${jdomVersion}</version>
    34. </dependency>
    35. <dependency>
    36. <groupId>log4j</groupId>
    37. <artifactId>log4j</artifactId>
    38. <version>${log4jVersion}</version>
    39. </dependency>
    40. <dependency>
    41. <groupId>jaxen</groupId>
    42. <artifactId>jaxen</artifactId>
    43. <version>${jaxenVersion}</version>
    44. </dependency>
    45. </dependencies>
    46. <build>
    47. <defaultGoal>install</defaultGoal>
    48. <plugins>
    49. <plugin>
    50. <groupId>org.apache.maven.plugins</groupId>
    51. <artifactId>maven-compiler-plugin</artifactId>
    52. <version>2.5.1</version>
    53. <configuration>
    54. <source>1.7</source>
    55. <target>1.7</target>
    56. <encoding>UTF-8</encoding> <!-- “编码 GBK 的不可映射字符”问题的解决 -->
    57. </configuration>
    58. </plugin>
    59. </plugins>
    60. </build>
    61. </project>



    通用的XML操作类(XMLOperatorUtils.java)


    1. package com.ll.myThreadStudy.MyThread;
    2. import java.util.List;
    3. import org.jdom.Element;
    4. import org.jdom.JDOMException;
    5. import org.jdom.xpath.XPath;
    6. public class XMLOperatorUtils {
    7. public static String getElementAttributeStringValue(Element element,
    8. String AttributeName) {
    9. try {
    10. return element.getAttributeValue(AttributeName);
    11. } catch (Exception e) {
    12. return null;
    13. }
    14. }
    15. public static Integer getElementAttributeIntegerValue(Element element,
    16. String AttributeName) {
    17. try {
    18. return Integer.parseInt(getElementAttributeStringValue(element,
    19. AttributeName));
    20. } catch (Exception e) {
    21. return -1;
    22. }
    23. }
    24. public static Long getElementAttributeLongValue(Element element,
    25. String AttributeName) {
    26. try {
    27. return Long.parseLong(getElementAttributeStringValue(element,
    28. AttributeName));
    29. } catch (Exception e) {
    30. return -1l;
    31. }
    32. }
    33. public static Boolean getElementAttributeBooleanValue(Element element,
    34. String AttributeName) {
    35. try {
    36. return Boolean.parseBoolean(getElementAttributeStringValue(element,
    37. AttributeName));
    38. } catch (Exception e) {
    39. return false;
    40. }
    41. }
    42. public static String getElementTextStringValueFromRoot(Element rootEle,
    43. String path) {
    44. try {
    45. return ((Element) getSingleNode(rootEle, path)).getTextTrim();
    46. } catch (Exception e) {
    47. return null;
    48. }
    49. }
    50. public static Integer getElementTextIntegerValueFromRoot(Element rootEle,
    51. String path) {
    52. try {
    53. return Integer.parseInt(getElementTextStringValueFromRoot(rootEle,
    54. path));
    55. } catch (Exception e) {
    56. return -1;
    57. }
    58. }
    59. public static Long getElementTextLongValueFromRoot(Element rootEle,
    60. String path) {
    61. try {
    62. return Long.parseLong(getElementTextStringValueFromRoot(rootEle,
    63. path));
    64. } catch (Exception e) {
    65. return -1l;
    66. }
    67. }
    68. public static Boolean getElementTextBooleanValueFromRoot(Element rootEle,
    69. String path) {
    70. try {
    71. return Boolean.parseBoolean(getElementTextStringValueFromRoot(
    72. rootEle, path));
    73. } catch (Exception e) {
    74. return false;
    75. }
    76. }
    77. public static String getElementTextStringValueByElement(Element element,
    78. String childName) {
    79. try {
    80. return element.getChildText(childName);
    81. } catch (Exception e) {
    82. return null;
    83. }
    84. }
    85. protected static Integer getElementTextIntegerValueByElement(
    86. Element element, String childName) {
    87. try {
    88. return Integer.parseInt(getElementTextStringValueByElement(element,
    89. childName));
    90. } catch (Exception e) {
    91. return -1;
    92. }
    93. }
    94. protected static Long getElementTextLongValueByElement(Element element,
    95. String childName) {
    96. try {
    97. return Long.parseLong(getElementTextStringValueByElement(element,
    98. childName));
    99. } catch (Exception e) {
    100. return -1l;
    101. }
    102. }
    103. protected static Boolean getElementTextBooleanValueByElement(
    104. Element element, String childName) {
    105. try {
    106. return Boolean.parseBoolean(getElementTextStringValueByElement(
    107. element, childName));
    108. } catch (Exception e) {
    109. return false;
    110. }
    111. }
    112. protected static Object getSingleNode(Element rootEle, String path)
    113. throws JDOMException {
    114. return XPath.selectSingleNode(rootEle, path);
    115. }
    116. @SuppressWarnings("rawtypes")
    117. protected static List getNodes(Element rootEle, String path)
    118. throws JDOMException {
    119. return XPath.selectNodes(rootEle, path);
    120. }
    121. }


    读取配置文件到Java POJO


    1. package com.ll.myThreadStudy.MyThread;
    2. import java.io.File;
    3. import java.util.ArrayList;
    4. import java.util.HashMap;
    5. import java.util.List;
    6. import org.apache.log4j.Logger;
    7. import org.jdom.Element;
    8. import org.jdom.input.SAXBuilder;
    9. import org.jdom.xpath.XPath;
    10. public class XmlToConfigVO {
    11. private static Logger logger = Logger.getLogger(XmlToConfigVO.class);
    12. public static MyConfigVo getLogSystemConfigVO(String fileName) {
    13. try {
    14. Element rootEle = new SAXBuilder().build(new File(fileName))
    15. .getRootElement();
    16. MyConfigVo myConfigVo = new MyConfigVo();
    17. //获取单个节点值的内容
    18. myConfigVo.setStringValue(XMLOperatorUtils
    19. .getElementTextStringValueFromRoot(rootEle,
    20. "/config/base-config/stringValue"));
    21. myConfigVo.setIntegerValue(XMLOperatorUtils
    22. .getElementTextIntegerValueFromRoot(rootEle,
    23. "/config/base-config/integerValue"));
    24. myConfigVo.setLongValue(XMLOperatorUtils
    25. .getElementTextLongValueFromRoot(rootEle,
    26. "/config/base-config/longValue"));
    27. //获取多个节点值
    28. HashMap<Integer, BookVo> booksMap = new HashMap<Integer, BookVo>();
    29. for (Object element : XPath.selectNodes(rootEle,"/config/books/book")) {
    30. BookVo book = new BookVo();
    31. book.setId(XMLOperatorUtils.getElementAttributeIntegerValue((Element) element,"id"));
    32. book.setName(XMLOperatorUtils.getElementTextStringValueByElement((Element) element,"name"));
    33. book.setPrice(XMLOperatorUtils.getElementTextLongValueByElement((Element) element,"price"));
    34. booksMap.put(book.getId(),book);
    35. }
    36. myConfigVo.setBooksMap(booksMap);
    37. List<ComputerVo> computerList= new ArrayList<ComputerVo>();
    38. for (Object element : XPath.selectNodes(rootEle,"/config/computers/computer")) {
    39. ComputerVo computer = new ComputerVo();
    40. computer.setType(XMLOperatorUtils.getElementAttributeStringValue((Element) element, "type"));
    41. computer.setSize(XMLOperatorUtils.getElementAttributeStringValue((Element) element,"size"));
    42. computerList.add(computer);
    43. }
    44. myConfigVo.setComputerList(computerList);
    45. return myConfigVo;
    46. } catch (Exception e) {
    47. logger.error(e);
    48. }
    49. return null;
    50. }
    51. }


    完整程序



    1. package com.ll.myThreadStudy.MyThread;
    2. import java.util.ArrayList;
    3. import java.util.HashMap;
    4. import java.util.List;
    5. public class MyConfigVo {
    6. private String stringValue;
    7. private Integer integerValue;
    8. private Long longValue;
    9. private HashMap<Integer, BookVo> booksMap = new HashMap<Integer, BookVo>();
    10. private List<ComputerVo> computerList = new ArrayList<ComputerVo>();
    11. public String getStringValue() {
    12. return stringValue;
    13. }
    14. public void setStringValue(String stringValue) {
    15. this.stringValue = stringValue;
    16. }
    17. public Integer getIntegerValue() {
    18. return integerValue;
    19. }
    20. public void setIntegerValue(Integer integerValue) {
    21. this.integerValue = integerValue;
    22. }
    23. public Long getLongValue() {
    24. return longValue;
    25. }
    26. public void setLongValue(Long longValue) {
    27. this.longValue = longValue;
    28. }
    29. public HashMap<Integer, BookVo> getBooksMap() {
    30. return booksMap;
    31. }
    32. public void setBooksMap(HashMap<Integer, BookVo> booksMap) {
    33. this.booksMap = booksMap;
    34. }
    35. public List<ComputerVo> getComputerList() {
    36. return computerList;
    37. }
    38. public void setComputerList(List<ComputerVo> computerList) {
    39. this.computerList = computerList;
    40. }
    41. @Override
    42. public int hashCode() {
    43. final int prime = 31;
    44. int result = 1;
    45. result = prime * result
    46. + ((booksMap == null) ? 0 : booksMap.hashCode());
    47. result = prime * result
    48. + ((computerList == null) ? 0 : computerList.hashCode());
    49. result = prime * result
    50. + ((integerValue == null) ? 0 : integerValue.hashCode());
    51. result = prime * result
    52. + ((longValue == null) ? 0 : longValue.hashCode());
    53. result = prime * result
    54. + ((stringValue == null) ? 0 : stringValue.hashCode());
    55. return result;
    56. }
    57. @Override
    58. public String toString() {
    59. return "MyConfigVo [stringValue=" + stringValue + ", integerValue="
    60. + integerValue + ", longValue=" + longValue + ", booksMap="
    61. + booksMap + ", computerList=" + computerList + "]";
    62. }
    63. @Override
    64. public boolean equals(Object obj) {
    65. if (this == obj)
    66. return true;
    67. if (obj == null)
    68. return false;
    69. if (getClass() != obj.getClass())
    70. return false;
    71. MyConfigVo other = (MyConfigVo) obj;
    72. if (booksMap == null) {
    73. if (other.booksMap != null)
    74. return false;
    75. } else if (!booksMap.equals(other.booksMap))
    76. return false;
    77. if (computerList == null) {
    78. if (other.computerList != null)
    79. return false;
    80. } else if (!computerList.equals(other.computerList))
    81. return false;
    82. if (integerValue == null) {
    83. if (other.integerValue != null)
    84. return false;
    85. } else if (!integerValue.equals(other.integerValue))
    86. return false;
    87. if (longValue == null) {
    88. if (other.longValue != null)
    89. return false;
    90. } else if (!longValue.equals(other.longValue))
    91. return false;
    92. if (stringValue == null) {
    93. if (other.stringValue != null)
    94. return false;
    95. } else if (!stringValue.equals(other.stringValue))
    96. return false;
    97. return true;
    98. }
    99. }


    1. package com.ll.myThreadStudy.MyThread;
    2. public class ComputerVo {
    3. private String type;
    4. private String size;
    5. public String getType() {
    6. return type;
    7. }
    8. public void setType(String type) {
    9. this.type = type;
    10. }
    11. public String getSize() {
    12. return size;
    13. }
    14. public void setSize(String size) {
    15. this.size = size;
    16. }
    17. @Override
    18. public String toString() {
    19. return "ComputerVo [type=" + type + ", size=" + size + "]";
    20. }
    21. }


    1. package com.ll.myThreadStudy.MyThread;
    2. public class BookVo {
    3. private Integer id;
    4. private String name;
    5. private Long price;
    6. public Integer getId() {
    7. return id;
    8. }
    9. public void setId(Integer id) {
    10. this.id = id;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public Long getPrice() {
    19. return price;
    20. }
    21. public void setPrice(Long price) {
    22. this.price = price;
    23. }
    24. @Override
    25. public String toString() {
    26. return "BookVo [id=" + id + ", name=" + name + ", price=" + price + "]";
    27. }
    28. }


    测试文件


    1. package com.ll.myThreadStudy.MyThread;
    2. public class Main {
    3. public static void main(String args[]) {
    4. MyConfigVo myConfigVo = XmlToConfigVO.getLogSystemConfigVO("d:\myConfig.xml");
    5. System.out.println(myConfigVo);
    6. }
    7. }


    测试结果









    附件列表

    • 相关阅读:
      获取Mac地址
      GbkToUtf8 Utf8ToGbk PackHttp
      first Automation
      win32 Dll 中添加afx.h 出现如下错误 error LNK2005: _DllMain@12 already defined
      OpenSUSE 开启SSH 和网络设置
      systemctl命令用法详解
      浅谈Python的列表和链表
      用Python实现最大堆
      写一个解二阶魔方的程序
      暴力破解SixPack问题
    • 原文地址:https://www.cnblogs.com/ssslinppp/p/4954451.html
    Copyright © 2020-2023  润新知