gpt4 book ai didi

java - 如何解析嵌套的 XML 数据并仅从中提取用户标识?

转载 作者:数据小太阳 更新时间:2023-10-29 02:56:49 34 4
gpt4 key购买 nike

我有下面的 xml 布局,我想从中提取 <key> </key> 内的所有“userid”值并将它们加载到 HashSet在Java中

<?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目的?我在这里做错什么了吗?

最佳答案

StAX 是解析大型 xml 的有效方法

    XMLStreamReader r = XMLInputFactory.newInstance().createXMLStreamReader(is);
while(r.hasNext()) {
if (r.next() == XMLStreamReader.START_ELEMENT && r.getLocalName().equals("value")) {
String value = r.getElementText();
System.out.println(value);
}
}

关于java - 如何解析嵌套的 XML 数据并仅从中提取用户标识?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27308966/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com