2011-11-28 104 views
2

列出我有像下面的例子SOAP响应一个XML数据:提取XML信息使用XPath

<EMP> 
    <PERSONAL_DATA> 
    <EMPLID>AA0001</EMPLID> 
    <NAME>Adams<NAME> 
    </PERSONAL_DATA> 
    <PERSONAL_DATA> 
    <EMPLID>AA0002<EMPLID> 
    <NAME>Paul<NAME> 
    </PERSONAL_DATA> 
</EMP> 

我想存储有关在Map(KEY,VALUE) KEY=tagname, VALUE=value 每个员工的信息,并希望创建一个LIST<MAP>适用于在java中使用XPATH的所有员工。这是如何完成的?

我尝试以下:

public static List createListMap(String path, SOAPMessage response,Map map) { 
      List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();  
       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<String, Object> map1 = new HashMap<String, Object>(); 
         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 ...我该如何做?

回答

2

表达式//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<Map<String, String>> fromNodeList(final NodeList nodes) { 
    final List<Map<String, String>> out = new ArrayList<Map<String,String>>(); 
    int len = (nodes != null) ? nodes.getLength() : 0; 
    for (int i = 0; i < len; i++) { 
     NodeList children = nodes.item(i).getChildNodes(); 
     Map<String, String> childMap = new HashMap<String, String>(); 
     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<Map<String, String>> nodes = fromNodeList(eval(doc, "//PERSONAL_DATA")); 
System.out.println(nodes); 

输出:

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

如果你实际处理更复杂的结构,具有额外的嵌套元素(我怀疑你是),那么你需要分别迭代这些图层或使用一些模型来为你的数据建模像JAXB

+1

非常感谢你 – Sandeep