使用XPath将XML信息提取到List

我有来自SOAP Response的XML数据,如下例所示:

  AA0001 Adams   AA0002 Paul   

我想在Map(KEY,VALUE) KEY=tagname, VALUE=value存储有关每个员工的信息Map(KEY,VALUE) KEY=tagname, VALUE=value并希望为在java中使用XPATH的所有员工创建LIST 。 这是怎么做到的?

我尝试了以下方法:

  public static List createListMap(String path, SOAPMessage response,Map map) { List<Map> list = new ArrayList<Map>(); try { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//" + path + "/*"); Object re =expr.evaluate(response.getSOAPBody(), XPathConstants.NODESET); NodeList nodes = (NodeList)res; for (int i = 0; i < nodes.getLength(); i++) { if (nodes.item(i).getFirstChild() != null && nodes.item(i).getFirstChild().getNodeType() == 1) { Map map1 = new HashMap(); map.put(nodes.item(i).getLocalName(), map1); createListMap(nodes.item(i).getNodeName(), response,map1); list.add(map); } else { map.put(nodes.item(i).getLocalName(),nodes.item(i).getTextContent()); } return list; } 

我调用了一个类似createListMap("EMP",response,map); (响应是SoapResponse)。 在XPATH //PERSONAL_DATA/* 。 在递归中,它列出了关于两个员工的数据,但我想将每个员工的数据存储在自己的地图中,然后创建这些MAP的LIST ……我该怎么做?

表达式//PERSONAL_DATA/*选择每个PERSONAL_DATA元素的所有子元素,从而导致您描述的问题。 相反,选择PERSONAL_DATA元素本身并迭代他们的孩子。

例:

 public NodeList eval(final Document doc, final String pathStr) throws XPathExpressionException { final XPath xpath = XPathFactory.newInstance().newXPath(); final XPathExpression expr = xpath.compile(pathStr); return (NodeList) expr.evaluate(doc, XPathConstants.NODESET); } public List> fromNodeList(final NodeList nodes) { final List> out = new ArrayList>(); int len = (nodes != null) ? nodes.getLength() : 0; for (int i = 0; i < len; i++) { NodeList children = nodes.item(i).getChildNodes(); Map childMap = new HashMap(); for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) childMap.put(child.getNodeName(), child.getTextContent()); } out.add(childMap); } return out; } 

像这样使用:

 List> nodes = fromNodeList(eval(doc, "//PERSONAL_DATA")); System.out.println(nodes); 

输出:

 [{NAME=Adams, EMPLID=AA0001}, {NAME=Paul, EMPLID=AA0002}] 

如果你实际上正在处理一个更复杂的结构,使用额外的嵌套元素(我怀疑你是这样),那么你需要单独迭代这些层或使用类似JAXB的数据建模数据。