2011-11-28 150 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