【发布时间】:2011-11-28 12:57:41
【问题描述】:
我有一个来自 SOAP 响应的 XML 数据,如下例所示:
<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
并希望在 java 中使用 XPATH 为所有员工创建一个LIST<MAP>。这是怎么做到的?
我尝试了以下方法:
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 的列表......我该怎么做?
【问题讨论】: