我有以下 xml 文件:
<parsedResponseMap>
<entry>
<key>SequenceID</key>
<value>3258</value>
</entry>
<entry>
<key>messageID</key>
<value>11</value>
</entry>
<entry>
<key>ConnectionID</key>
<value>1</value>
</entry>
</parsedResponseMap>
在上面的 XML 中,我只需要 11(messageID 键的值)。我有性能问题。如果我解析 xml,那么我的性能就会下降,我只需要 xml 中的一个值。所以我可以通过任何其他方式获得更好性能的值(value)。
最佳答案
public class ExtractValueFromXml {
public static void main(String[] args) throws IOException {
String lineBefore = "<key>messageID</key>";
Pattern pattern = Pattern.compile("<value>(.+?)</value>");
String numberFound = null;
try (BufferedReader br = new BufferedReader(new FileReader("file.xml"))) {
String line = null;
while ((line = br.readLine()) != null) {
if (line.matches(lineBefore)) {
Matcher matcher = pattern.matcher(br.readLine());
if (matcher.find()) {
numberFound = matcher.group(1);
break;
}
}
}
System.out.println(numberFound);
} catch (Exception e) {
}
}
}
关于java - 如何在java中不解析xml获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33295579/