目前我正在使用这种方法在 XML 文档中查找指定的标签:
public static String parseDocument(byte[] stream, String tagName, String resourceName) {
String result = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(stream));
document.getDocumentElement().normalize();
Node tag = document.getElementsByTagName(tagName).item(0);
result = tag.getAttributes().getNamedItem(resourceName).getNodeValue();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
但这只返回第一个匹配项。如何实现返回所有找到的标签的方法?
最佳答案
NodeList tags = document.getElementsByTagName(tagName);
List<String> values = new ArrayList<String>();
for (int i = 0 ; i < tags.getLength() ; i++) {
values.add(tags.item(i).getNodeValue());
}
关于java - 如何查找 XML 文档中的所有标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8357854/