好记性不如烂笔头60-利用XMLConfiguration解析XML多节点

前端之家收集整理的这篇文章主要介绍了好记性不如烂笔头60-利用XMLConfiguration解析XML多节点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

利用XMLConfiguration解析XML多节点.

1、 用XMLConfiguration解析XML多节点的源代码

  1. package test.ffm83.commons.configuration;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.io.InputStream;
  5. import java.util.List;
  6.  
  7. import org.apache.commons.configuration.HierarchicalConfiguration;
  8. import org.apache.commons.configuration.HierarchicalConfiguration.Node;
  9. import org.apache.commons.configuration.XMLConfiguration;
  10.  
  11. /** * 简单示例,解析XML多个同类型子节点属性,比如输出XY坐标 * * @author 范芳铭 */
  12. public class EasyParseNodesXML {
  13. //解析子节点
  14. private static String parseMutliLines(HierarchicalConfiguration lineConfig) {
  15. String value = "";
  16. Node root = lineConfig.getRoot();
  17. List children = root.getChildren();
  18.  
  19. int count = 0;
  20. for (int i = 0; i < children.size(); i++) {
  21. Node child = (Node) children.get(i);
  22. if ("point".equals(child.getName())) {
  23. count++;
  24. }
  25. }
  26. for (int i = 0; i < count; i++) {
  27. value += lineConfig.getString("point(" + i + ")[@X]");
  28. value += ",";
  29. value += lineConfig.getString("point(" + i + ")[@Y]");
  30. value += ":";
  31. }
  32. return value;
  33. }
  34.  
  35. public static void main(String[] args) throws Exception {
  36. String xml = "<csMsgReqs>"
  37. + " <csMsgReq xsi:type=\"cstypeNotify\">"
  38. + " <authority xsi:type=\"cstypeAuthorityCommon\"/>"
  39. + " <nbase xsi:type=\"cstypeAlarmGeneral\">"
  40. + " <alarmTime>2014-03-21 16:16:26.682</alarmTime>"
  41. + " <TrackLine xsi:type=\"cstypeTrackLineType\" lineLth=\"18\">"
  42. + " <point xsi:type=\"cstypepoint\" X=\"1211\" Y=\"351\"/>"
  43. + " <point xsi:type=\"cstypepoint\" X=\"1386\" Y=\"472\"/>"
  44. + " </TrackLine>" + " </nbase>"
  45. + " </csMsgReq>" + "</csMsgReqs>";
  46.  
  47. InputStream in = new ByteArrayInputStream(xml.getBytes());
  48. XMLConfiguration config = new XMLConfiguration();
  49.  
  50. try {
  51. config.load(in);
  52.  
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. }
  56.  
  57. String alarmTime = config.getString("csMsgReq.nbase.alarmTime");
  58. //将子节点作为参数传入
  59. HierarchicalConfiguration lineConfig = (HierarchicalConfiguration) config
  60. .subset("csMsgReq.nbase.TrackLine");
  61. String trackLine = parseMutliLines(lineConfig);
  62.  
  63. System.out.println("alarmTime:" + alarmTime);
  64. System.out.println("trackLine:" + trackLine);
  65. }
  66. }

2、 运行程序

alarmTime:2014-03-21 16:16:26.682 trackLine:1211,351:1386,472:

猜你在找的XML相关文章