2012-03-16 79 views
1

我怎么能解析XML这样SAX解析问题

<rss version="0.92"> 
<channel> 
<title>MyTitle</title> 
<link>http://myurl.com</link> 
<description>MyDescription</description> 
<lastBuildDate>SomeDate</lastBuildDate> 
<docs>http://someurl.com</docs> 
<language>SomeLanguage</language> 

<item> 
    <title>TitleOne</title> 
    <description><![CDATA[Some text.]]></description> 
    <link>http://linktoarticle.com</link> 
</item> 

<item> 
    <title>TitleTwo</title> 
    <description><![CDATA[Some other text.]]></description> 
    <link>http://linktoanotherarticle.com</link> 
</item> 

</channel> 
</rss> 

请任意一个帮助。

回答

1

试试这个

public class ExampleHandler extends DefaultHandler { 

private Channel channel; 
private Items items; 
private Item item; 
private boolean inItem = false; 

private StringBuilder content; 

public ExampleHandler() { 
    items = new Items(); 
    content = new StringBuilder(); 
} 

public void startElement(String uri, String localName, String qName, 
     Attributes atts) throws SAXException { 
    content = new StringBuilder(); 
    if(localName.equalsIgnoreCase("channel")) { 
     channel = new Channel(); 
    } else if(localName.equalsIgnoreCase("item")) { 
     inItem = true; 
     item = new Item(); 
    } 
} 

public void endElement(String uri, String localName, String qName) 
     throws SAXException { 
    if(localName.equalsIgnoreCase("title")) { 
     if(inItem) { 
      item.setTitle(content.toString()); 
     } else { 
      channel.setTitle(content.toString()); 
     } 
    } else if(localName.equalsIgnoreCase("link")) { 
     if(inItem) { 
      item.setLink(content.toString()); 
     } else { 
      channel.setLink(content.toString()); 
     } 
    } else if(localName.equalsIgnoreCase("description")) { 
     if(inItem) { 
      item.setDescription(content.toString()); 
     } else { 
      channel.setDescription(content.toString()); 
     } 
    } else if(localName.equalsIgnoreCase("lastBuildDate")) { 
     channel.setLastBuildDate(content.toString()); 
    } else if(localName.equalsIgnoreCase("docs")) { 
     channel.setDocs(content.toString()); 
    } else if(localName.equalsIgnoreCase("language")) { 
     channel.setLanguage(content.toString()); 
    } else if(localName.equalsIgnoreCase("item")) { 
     inItem = false; 
     items.add(item); 
    } else if(localName.equalsIgnoreCase("channel")) { 
     channel.setItems(items); 
    } 
} 

public void characters(char[] ch, int start, int length) 
     throws SAXException { 
    content.append(ch, start, length); 
} 

public void endDocument() throws SAXException { 
    // you can do something here for example send 
    // the Channel object somewhere or whatever. 
} 

} 

其中项目,项目和渠道是吸气setter方法类...

了解详情,请访问这个问题的How to parse XML using the SAX parser

+1

得益于快速回复....也有用 :) – 2012-03-16 06:05:20