如何查找XML文档中的所有标记?

时间:2011-12-02 14:30:43

标签: java xml

目前我正在使用此方法在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;

    }

但这只返回第一场比赛。如何实现返回所有找到的标签的方法?

1 个答案:

答案 0 :(得分:2)

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());
}