如何找出XML中是否存在标记?

时间:2014-02-03 10:47:04

标签: java xml

^ _ ^

我正在使用DOM Parser来解析XML数据。

我想知道是否存在标签。

例如..

<a>
  <aa>
  <bb>
</a>

在这个XML代码中,如果我想知道XML代码中存在<aa>,我该怎么做?

我还没找到路......T_T

如果你知道方式..请让我知道.. ^^ ;;

2 个答案:

答案 0 :(得分:1)

通过XPath:

    XPath path = XPathFactory.newInstance().newXPath();
    final Double count=(Double) path.evaluate("count(//bb)", doc, XPathConstants.NUMBER);
    System.out.println(count.intValue());

答案 1 :(得分:0)

使用SAX Parser

try {

SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);  // By Default also, it is false
factory.setNamespaceAware(true);

SAXParser parser = factory.newSAXParser();

XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new SimpleErrorHandler());
reader.parse(new InputSource("./configurationfiles/document.xml"));
} catch (SAXException e) {
   System.out.println(e.getMessage());
} catch (ParserConfigurationException e) {
   e.printStackTrace();
}

<强> SimpleErrorHandle.java

class SimpleErrorHandler implements ErrorHandler {
    public void warning(SAXParseException e) throws SAXException {
        System.out.println(e.getMessage());
    }

    public void error(SAXParseException e) throws SAXException {
        System.out.println(e.getMessage());
    }

    public void fatalError(SAXParseException e) throws SAXException {
        System.out.println(e.getMessage());
    }
}

使用DOM Parser

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);  // By Default also, it is false
    factory.setNamespaceAware(true);

    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();

        builder.setErrorHandler(new SimpleErrorHandler());

        Document document = builder.parse(new InputSource("./configurationfiles/document.xml"));
    } catch (SAXException e) {
        System.out.println(e.getMessage());
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

<强>输出

The element type "bb" must be terminated by the matching end-tag "</bb>".