【发布时间】:2015-02-03 05:08:54
【问题描述】:
我有下面的xml布局,我想从中提取<key> </key>中的所有“userid”值并将它们加载到Java中的HashSet
<?xml version="1.0" encoding="UTF-8"?>
<response>
<plds>
<fld>consumerid</fld>
<fld>last_set</fld>
</plds>
<record>
<data>934463448 1417753752</data>
<key_data>
<key>
<name>userid</name>
<value>934463448</value>
</key>
</key_data>
</record>
<record>
<data>1228059948 1417753799</data>
<key_data>
<key>
<name>userid</name>
<value>1228059948</value>
</key>
</key_data>
</record>
</response>
我将从一个 url 获取以上 xml 数据,并且有可能我可以获得大的 XML 文件。解析上述 XML 并提取所有“userid”并将其加载到 Java 中的 HashSet 中的最佳方法是什么?
这就是我开始的 -
public static Set<String> getUserList(String host, String count) {
Set<String> usrlist = new HashSet<String>();
String url = "urlA"; // this url will return me above XML data
InputStream is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
// not sure what I should do here which can
// parse my above xml and extract all the
// userid and load it into usrlist hash set
return usrlist;
}
更新:-
这是我尝试过的 -
public static Set<String> getUserList() {
Set<String> usrlist = new HashSet<String>();
String url = "urlA"; // this url will return me above XML data
InputStream is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new URL(url).openStream());
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//record/key_data/key[name='userid']/value");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
usrlist.add(nodes.item(i).getNodeValue());
}
return usrlist;
}
但是我在usrlist 对象中没有得到任何用户ID?我在这里做错什么了吗?
【问题讨论】:
-
为什么不使用杰克逊?
-
像 JAXB 这样的东西可以提供帮助吗?但它与 xpath 在相同的环境中工作。整个文档将在内存中。
-
@alkis 您能否提供一个示例,我如何在这里使用 JAXB?我以前从未使用过 JAXB。
-
当然。请检查我的答案。虽然我知道认为这是矫枉过正。
-
以下任何答案有帮助吗?