开发者

XML Parsing to get Attribute Value

开发者 https://www.devze.com 2023-03-18 03:21 出处:网络
I am parsing a xml using SAX Parser. Everythings working fine when the data I need to get is the body of a xml tag. The only problem I am getting is when the data I need is the attribute value of that

I am parsing a xml using SAX Parser. Everythings working fine when the data I need to get is the body of a xml tag. The only problem I am getting is when the data I need is the attribute value of that XML tag. How do i开发者_JAVA百科 get this attribute value?

<xml att="value"> Body </xml>

Suppose this is a tag, I am able to get Body but not value

code I am using is:

URL url = new URL("http://example.com/example.xml");

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();

XMLReader xr = sp.getXMLReader();
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);

xr.parse(new InputSource(url.openStream()));

public class ExampleHandler extends DefaultHandler { 
String buff = new String("");
boolean buffering = false; 

@Override
public void startDocument() throws SAXException {
    // Some sort of setting up work
} 

@Override
public void endDocument() throws SAXException {
    // Some sort of finishing up work
} 

@Override
public void startElement(String namespaceURI, String localName, String qName, 
        Attributes atts) throws SAXException {
    if (localName.equals("qwerasdf")) {
        buff = new String("");
        buffering = true;
    }   
} 

@Override
public void characters(char ch[], int start, int length) {
    if(buffering) {
        buff=new String(ch, start, length)
    }
} 

@Override
public void endElement(String namespaceURI, String localName, String qName) 
throws SAXException {
    if (localName.equals("blah")) {
        buffering = false; 
        String content = buff.toString();

        // Do something with the full text content that we've just parsed
    }
}


@Override
public void startElement(String namespaceURI, String localName, String qName, 
        Attributes atts) throws SAXException {
    if (localName.equals("xml")) {
          System.out.println("The value of attribute 'att' is: " + atts.getValue("att"));
    }   
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号