简体   繁体   English

如何使用SAX Parser解析并获取具有特定类的div元素

[英]How to parse and obtain a div element with a particular class using the SAX Parser

This is a snippet of my XML file 这是我的XML文件的片段

<name>Jason</name>
<div class="title">Domain Architect</div>

How do I parse using SAX Parser and obtain the div element with the particular class "title" ? 如何使用SAX Parser解析并获取具有特定类“title”的div元素?

I am able to parse and obtain all the div elements. 我能够解析并获得所有div元素。
Is there a simple way to obtain the elements that are of a particular class only. 是否有一种简单的方法来获取仅特定类的元素。

EDIT : 编辑:

This is how my handler is : 这就是我的处理程序:

DefaultHandler handler = new DefaultHandler() {

boolean bfname = false;
boolean bdesig = false;

public void startElement(String uri, String localName,String qName, 
            Attributes attributes) throws SAXException {



    if (qName.equalsIgnoreCase("name")) {
        bfname = true;
    }

    if((qName.equalsIgnoreCase("div"))) {
        bdesig = true;
    }


}

public void characters(char ch[], int start, int length) throws SAXException {

    if (bfname) {
        System.out.println("Name : " + new String(ch, start, length));
        bfname = false;
    }

    if(bdesig) {
        System.out.println("Designation : " + new String(ch, start, length));
        bdesig = false;
    }

}

 };

In startElement() the class attribute can be evaluated from the attributes . startElement() ,可以从attributes评估class attributes You then could set a flag if there is an attribute class and you are interested in this particular class (its value). 然后,如果存在属性class并且您对此特定类(其值)感兴趣,则可以设置标志。 Reset the flag if you are not. 如果不是,请重置标志。 Evaluate this flag in characters to retrieve the text contents of the element. characters计算此标志以检索元素的文本内容。

For small documents and non-critical performance you could use XPath to solve this in a more elegant way. 对于小文档和非关键性能,您可以使用XPath以更优雅的方式解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM