user1859150
user1859150

Reputation: 11

How to get tag name in sax xml parsing in java

I am able to get John,B and 12 by childNodeLst.item(k).getTextContent().But how I will get name,grade and age ?? In this xml

<students> <student> <name>John</name> <grade>B</grade> <age>12</age> </student> </students>

Upvotes: 1

Views: 934

Answers (2)

Chris Nitchie
Chris Nitchie

Reputation: 557

It looks like you're asking about DOM, not SAX. With DOM, you'd do something like this:

private String getChildNodeContent(Element parentNode, String tagName) {
    NodeList children = parentNode.getElementsByTagName(tagName);
    return children.length == 0 ? null : children.item(0).getTextContent();
}
...
Element student = (Element) childNodeList.item(k);
String name = getChildNodeContent(student, "name");
String grade = getChildNodeContent(student, "grade");
String age = getChildNodeContent(student, "age");

In SAX, you have to watch startElement() and endElement() go by looking for the start/end tags you care about, and capture characters() events to capture the text.

private StringBuilder buffer = new StringBuilder();

public void startElement(String uri, String lname, String qname, Attributes atts) {
    buffer.setLength(0);
}

public void endElement(String uri, String lname, String qname) {
    String tag = context.pop();
    String contents = buffer.toString();
    // Do something interesting with 'contents' for the given tag.
    buffer.setLength(0);
}

public void characters(char[] ch, int start, int len) {
    buffer.append(ch, start, len);
}

Upvotes: 2

3stones
3stones

Reputation: 183

public void characters(char[] ch, int start, int length) throws SAXException {
if(preTag!=null){
String content = new String(ch,start,length);
if("name".equals(preTag)){
student.setName(content);
}else if("age".equals(preTag)){
student.setAge(Float.parseFloat(content));
}
}
}

Upvotes: 0

Related Questions