美文网首页
XPath获取XML指定节点属性值的两种方法

XPath获取XML指定节点属性值的两种方法

作者: java高级架构F六 | 来源:发表于2019-12-04 22:24 被阅读0次

    前面有文章介绍了通过XPath解析xml报文的方法,今天工作中遇到了需要解析指定节点属性值的问题,现在总结一下,下面提供两种方法去获取属性值。

    首先是xml结构:

    1.<?xml version="1.0" encoding="utf-8" ?>

    2.<bookstore>

    3. <book>

    4. <title lang="en1">Everyday Italian</title>

    5. <author>Giada De Laurentiis</author>

    6. <year>2005</year>

    7. <price>30.00</price>

    8.</book>

    9.<book>

    10.<title lang="en2">Harry Potter</title>

    11.<author>J K. Rowling</author>

    12. <year>2005</year>

    13. <price>29.99</price>

    14.</book>

    15. <book>

    16. <title lang="en3">Learning XML</title>

    17. <author>Erik T. Ray</author>

    18.<year>2003</year>

    19.<price>39.95</price>

    20. </book>

    21.</bookstore>

    解析代码:

    1.import org.w3c.dom.Document;

    2.import org.w3c.dom.Node;

    3.import org.w3c.dom.NodeList;

    4.import org.xml.sax.SAXException;

    5.

    6.import javax.xml.parsers.DocumentBuilderFactory;

    7.import javax.xml.parsers.ParserConfigurationException;

    8.import javax.xml.transform.Transformer;

    9.import javax.xml.transform.TransformerException;

    10.import javax.xml.transform.TransformerFactory;

    11.import javax.xml.transform.dom.DOMSource;

    12.import javax.xml.transform.stream.StreamResult;

    13.import javax.xml.xpath.XPath;

    14import javax.xml.xpath.XPathConstants;

    15.import javax.xml.xpath.XPathFactory;

    16.import java.io.*;

    17.

    18./**

    19.* Created by hasee on 2017/2/14.

    20. * liqinghe

    21. * 获取xml指定节点属性值

    22. */

    23.public class PropertyValueTest {

    24.

    25. public static void main(String[] args) throws Exception {

    26. //XML文档路径

    27. String xmlUrl = "D:\\FTP\\测试XML\\book.xml";

    28. //需要获取的节点属性值位置

    29. String propertyUrl = "bookstore/book/title";

    30. String propertyName = "lang";

    31. Document document = getXmlDocument(xmlUrl);

    32. //获取该位置的节点集合

    33. NodeList nodeList = nodeList(propertyUrl, document);

    34.

    35. //第一种方法 node直接获取

    36. for (int i = 0; i < nodeList.getLength(); i++) {

    37. Node node = nodeList.item(i);

    38. Node attr = node.getAttributes().getNamedItem(propertyName);

    39. String propertyValue = attr.getNodeValue(); //属性值

    40. System.out.println(propertyValue);

    41. }

    42.

    43. //第二种方法 用xpath获取

    44. for (int i = 0; i < nodeList.getLength(); i++) {

    45. Node node = nodeList.item(i);

    46. //将node对象转成string字符串

    47. String nodeString = NodetoString(node);

    48. Document document1 =stringDoc(nodeString);

    49. //注意需要用到@符号

    50. String path = "title"+"/@"+propertyName;

    51. String propertyValue = propertyValue(path,document1); //属性值

    52. System.out.println(propertyValue);

    53. }

    54. }

    55.

    56. /**

    57. * 根据xml文档路径生成Document对象

    58. *

    59. * @param xmlFilePath XML文档路径

    60. * @return Document

    61. */

    62. public static Document getXmlDocument(String xmlFilePath) {

    63. Document doc = null;

    64. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    65. dbf.setNamespaceAware(true);

    66. try {

    67. doc = dbf.newDocumentBuilder().parse(new FileInputStream(xmlFilePath));

    68. } catch (ParserConfigurationException ex) {

    69. ex.printStackTrace();

    70. } catch (FileNotFoundException ex) {

    71. ex.printStackTrace();

    72. } catch (SAXException ex) {

    73. ex.printStackTrace();

    74. } catch (IOException ex) {

    75. ex.printStackTrace();

    76. }

    77. return doc;

    78. }

    79.

    80. /**

    81. * 获取节点集合

    82. *

    83. * @param path 节点位置 head/MessageID

    84. * @param document

    85. * @return

    86. */

    87. public static NodeList nodeList(String path, Node document) {

    88. NodeList nodeList = null;

    89. try {

    90. // 生成XPath对象

    91. XPath xpath = XPathFactory.newInstance().newXPath();

    92. // 获取节点值

    93. nodeList = (NodeList) xpath.evaluate(

    94. path, document,

    95. XPathConstants.NODESET);

    96. } catch (Exception e) {

    97. }

    98. return nodeList;

    99. }

    100.

    101.

    102. /**

    103. * string 转换成 doc

    104. * @param docStr

    105 * @return

    106. * @throws Exception

    107. */

    108. public static Document stringDoc(String docStr) throws Exception {

    109. InputStream is = new ByteArrayInputStream(docStr.getBytes());

    110. Document doc = null;

    111. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    112. dbf.setNamespaceAware(true);

    113. try {

    114. doc = dbf.newDocumentBuilder().parse(is);

    115. } catch (ParserConfigurationException ex) {

    116. ex.printStackTrace();

    117. } catch (FileNotFoundException ex) {

    118. ex.printStackTrace();

    119. } catch (SAXException ex) {

    120. ex.printStackTrace();

    121. } catch (IOException ex) {

    122. ex.printStackTrace();

    123. }

    124. return doc;

    125. }

    126.

    127. /**

    128. * 获取节点属性值

    129. * @param path 节点属性值位置 head/@propertyName

    130. * @param node xml对象

    131. * @return

    132. */

    133. public static String propertyValue(String path, Node node) {

    134. String nodeValue = "";

    135. try {

    136. // 生成XPath对象

    137. XPath xpath = XPathFactory.newInstance().newXPath();

    138. // 获取节点值

    139. nodeValue = (String) xpath.evaluate(

    140. path, node,

    141. XPathConstants.STRING);

    142. } catch (Exception e) {

    143. }

    145. return nodeValue;

    146. }

    147.

    148. /**

    149. * 将传入的一个DOM Node对象输出成字符串。如果失败则返回一个空字符串""。

    150. *

    151. * @param node DOM Node 对象。

    152. * @return a XML String from node

    153. */

    154. public static String NodetoString(Node node) {

    155. Transformer transformer = null;

    156. String result = null;

    157. if (node == null) {

    158. throw new IllegalArgumentException();

    159. }

    160. try {

    161. transformer = TransformerFactory.newInstance().newTransformer();

    162. } catch (Exception e) {

    163. throw new RuntimeException(e.getMessage());

    164. }

    165. if (transformer != null) {

    166. try {

    167. StringWriter sw = new StringWriter();

    168. transformer.transform(new DOMSource(node), new StreamResult(sw));

    169. return sw.toString();

    170. } catch (TransformerException te) {

    171. throw new RuntimeException(te.getMessage());

    172. }

    173. }

    174. return result;

    175. }

    176.}

    代码注释写得很清楚了,注意所用的Document是 w3c下面的。

    运行结果:

    1.en1

    2.en2

    3.en3

    4.en1

    5.0en2

    6.en3

    相关文章

      网友评论

          本文标题:XPath获取XML指定节点属性值的两种方法

          本文链接:https://www.haomeiwen.com/subject/dsdrgctx.html