SAX, DOM都可以用来解析xml,问的人太多,今天自己又用到还是写一下吧
<
uses-permission
android:name
=
"android.permission.INTERNET"
/>
几乎没有什么人是解析单机版的吧
public class CurrencyXMLReader
{
private String urlM;
public CurrencyXMLReader( String theUrl)
{
urlM = theUrl;
}
public CurrencyList obtainCurrencyList() throws ParserConfigurationException,
SAXException,
IOException
{
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
CurrencyXMLHandler currHandler = new CurrencyXMLHandler();
xmlReader.setContentHandler( currHandler);
URL url = new URL( urlM);
xmlReader.parse(new InputSource( url.openStream()));
return currHandler.getCurrencyList();
}
public class CurrencyXMLReader
{
private String urlM;
public CurrencyXMLReader( String theUrl)
{
urlM = theUrl;
}
public CurrencyList obtainCurrencyList() throws ParserConfigurationException,
SAXException,
IOException
{
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
CurrencyXMLHandler currHandler = new CurrencyXMLHandler();
xmlReader.setContentHandler( currHandler);
URL url = new URL( urlM);
xmlReader.parse(new InputSource( url.openStream()));
return currHandler.getCurrencyList();
}
内容
<gesmes:envelope>
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:sender>
<cube>
<cube time="2010-12-17">
<cube currency="USD" rate="1.3260"/>
<cube currency="JPY" rate="111.26"/>
<cube currency="BGN" rate="1.9558"/>
...
...
</cube>
</cube>
</gesmes:envelope>
使用
public class CurrencyXMLHandler extends DefaultHandler{
private CurrencyList currencyListM = new CurrencyList();
@Override
public void startElement( String theNamespaceURI,
String theLocalName,
String theQName,
Attributes theAtts) throws SAXException
{
if( theLocalName.equals("Cube"))
{
if( theAtts != null)
{
if( theAtts.getValue( "currency") != null)
{
String currency = theAtts.getValue("currency");
String rate = theAtts.getValue( "rate");
currencyListM.add( new CurrencyData( currency, rate));
}
else if( theAtts.getValue( "time") != null)
{
currencyListM.setDataDate( theAtts.getValue("time"));
}
}
}
}
CurrencyList getCurrencyList()
{
return currencyListM;
}