简体   繁体   中英

Parsing XML with attributes in Android

I am trying to parse an xml file (from assets) however I cannot get it right.

Usually when I do this the I would format my xml file like the following:

<channel>
  <item>
    <name>Hello Earth</name>
    <place>Earth</place>
  </item>
  <item>
    <name>Goodbye Mars</name>
    <place>Mars</place>
  </item/>
</channel>

And I would use the following code to parse out what I need:

AssetManager assetManager = getAssets();
InputStream inputStream = assetManager.open("words.xml");

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setCoalescing(true);
DocumentBuilder builder = factory.newDocumentBuilder();

Document dom = builder.parse(inputStream);      

org.w3c.dom.Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("item");     

String name="";
String place="";

for (int i = 0; i < items.getLength(); i++) {
Node item = items.item(i);
NodeList properties = item.getChildNodes();

for (int j = 0; j < properties.getLength(); j++) {
    Node property = properties.item(j);
    String propertyName = property.getNodeName();

    if (propertyName.equalsIgnoreCase("name")) {
        String strText = property.getFirstChild()
        .getNodeValue();
        nam = strText;
    }

    if (propertyName.equalsIgnoreCase("place")) {
        String strText = property.getFirstChild()
        .getNodeValue();
        place = strText;
    }

    db.insertWord(name, place);
}

However the xml is coming from another source and it is formatted differently, it uses attributes instead since it was a mysql export. Here is the XML I must parse but I cannot figure out how I should this, I tried playing around with the getAttribute() methods but cant get the data out of the xml:

<table name="item">
  <column name="name">Hello Earth</column>
  <column name="place">Earth</column>
</table>
<table name="item">
  <column name="name">Goodbye Mars</column>
  <column name="place">Mars</column>
</table>

Try these ......

1. DOM PARSER

2. SAX PARSER

3. JAXB AND JAXP

4. CASTOR

5. Pull Parser

you can try this using pull parser as follow..

//define class item

class Item
{
   String name;
   String place;
}



 ArrayList<Item>items=new ArrayList<Item>();




void somemethod()
{

AssetManager assetManager = getAssets();
 InputStream inputStream = assetManager.open("words.xml");

Item item=new Item();
try
        {
             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
             factory.setNamespaceAware(true);
             XmlPullParser xpp = factory.newPullParser();
             xpp.setInput(inputStream,null);
             int eventType = xpp.getEventType();
             while (eventType != XmlPullParser.END_DOCUMENT) 
             {
                 if(eventType == XmlPullParser.START_DOCUMENT) 
                  { }                 
                 else if(eventType == XmlPullParser.START_TAG)
                 {
                     try 
                     {                          
                             if(xpp.getName()!=null&& xpp.getName().equalsIgnoreCase("name"))
                              {
                                   eventType = xpp.next();
                                   item.name=Integer.parseInt(xpp.getText().toString());
                              }
                             else if(xpp.getName()!=null&& xpp.getName().equalsIgnoreCase("place"))
                              {
                                   eventType = xpp.next();
                                   item.place=xpp.getText().toString();
                              }                     
                        } 
                     catch (Exception e) 
                        {
                            //e.printStackTrace();
                        }
                 }
                 else if(eventType == XmlPullParser.END_TAG) 
                 {
                     if(xpp.getName()!=null&& xpp.getName().equalsIgnoreCase("content"))
                      {
                           eventType = xpp.next();  
                           items.put(item);
                           item=new Item();
                      }
                 }
                 else if(eventType == XmlPullParser.TEXT) 
                 {}
                 eventType = xpp.next();       
         }// end of while                    

        }
        catch (XmlPullParserException e) 
        {
            //e.printStackTrace();
        } 
        catch (IOException e) 
        {
          //e.printStackTrace();
        }
        finally
        {
            try 
            {
                if(inputStream!=null)
                    inputStream.close();
            } catch (IOException e) 
            {               
            }
        }


    }

Take a look at the answer to this questions. There is an example of how to handle attributes:

how do I extract text from a nested xml using xmlpullparser in android?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM