2010-07-11 79 views
2

我需要使用的API不支持xpath,這有點令人頭疼! :-(笑Android中的XML解析[Java]

我想解析XML是作爲一個字符串我的問題:

  1. 是否有相當於Java「simplexml_load_string」,它使串入解析XML文檔的?
  2. 這是用於解析,SAX或DOM更好嗎?我需要一對夫婦的價值觀出了XML和結構不深。[3級]

謝謝!

回答

1

也許這將幫助你

//http://developer.android.com/intl/de/reference/android/content/res/XmlResourceParser.html 
import org.xmlpull.v1.XmlPullParserException; 
try { 
      XmlResourceParser xrp = ctx.getResources().getXml(R.xml.rules); 
      while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) { 
       if (xrp.getEventType() == XmlResourceParser.START_TAG) { 
        String s = xrp.getName(); 
        if (s.equals("category")) { 

         String catname = xrp.getAttributeValue(null, "name"); 

         String rule = xrp.getAttributeValue(null, "rule"); 



        } 
       } else if (xrp.getEventType() == XmlResourceParser.END_TAG) { 
        ; 
       } else if (xrp.getEventType() == XmlResourceParser.TEXT) { 
        ; 
       } 
       xrp.next(); 
      } 
      xrp.close(); 

     } catch (XmlPullParserException xppe) { 
      Log.e(TAG(), "Failure of .getEventType or .next, probably bad file format"); 
      xppe.toString(); 
     } catch (IOException ioe) { 
      Log.e(TAG(), "Unable to read resource file"); 
      ioe.printStackTrace(); 
     } 
0
  1. 不知道。
  2. 如果XML文件/字符串很小,那麼DOM是一個不錯的選擇,因爲它提供了更多的功能。 SAX應該用於需要內存使用和性能的較大XML文件。