-1

嗨,伙计们,我对 xml 解析有问题,我有以下必须解析的 xml,但我很困惑如何解析这个。我已经关注这个

<Root>
<Category id="1" name="Live" subcategories="6">
<SubCategory id="1" name="Entertenment" subcategories="0"/>
<SubCategory id="2" name="Movies" subcategories="0"/>
<SubCategory id="3" name="Musics" subcategories="0"/>
<SubCategory id="4" name="Regional" subcategories="0"/>
<SubCategory id="5" name="Devotional" subcategories="0"/>
<SubCategory id="6" name="News" subcategories="4">
<ChildCategory id="1" name="International" subcategories="0"/>
<ChildCategory id="2" name="Politic" subcategories="0"/>
<ChildCategory id="3" name="Movies" subcategories="0"/>
<ChildCategory id="4" name="Celeberities" subcategories="0"/>
</SubCategory></Category>
</Root>

如果有任何解决方案,请建议我。

4

6 回答 6

1

使用 XMLPullParser。示例代码是解析 RSS 内容。

        try {
                // Standard code to make an HTTP connection.
                URL url = new URL(RSS_URL);
                URLConnection connection = url.openConnection();
                connection.setRequestProperty("User-agent", "Mozilla/4.0");
                connection.setConnectTimeout(20000);
                connection.connect();
                InputStream in = connection.getInputStream();

                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                factory.setNamespaceAware(true);
                XmlPullParser xpp = factory.newPullParser();
                xpp.setInput(in, null);

                int eventType;
                String title = "";
                String link = "";
                String description = "";
                String pubDate = "";
                eventType = xpp.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_TAG) {
                        String tag = xpp.getName();
                        if (tag.equals("item")) {
                            title = link = description = "";
                        } else if (tag.equals("title")) {
                            xpp.next();
                            title = xpp.getText();
                        } else if (tag.equals("link")) {
                            xpp.next();
                            link = xpp.getText();
                        } else if (tag.equals("description")) {
                            xpp.next();
                            description = xpp.getText();
                        } else if (tag.equals("pubDate")) {
                            xpp.next();
                            pubDate = xpp.getText();
                        }
                    } else if (eventType == XmlPullParser.END_TAG) {
                        String tag = xpp.getName();
                        if (tag.equals("item")) {
                            description = "    "
                                    + description.replaceAll("<a target.*<br>", "");
                            RssItem item = new RssItem();
                            item.mTitle = title;
                            item.mUrl = link;
                            item.mDescription = description;
                            item.mPubDate = pubDate;
                            item.mMD5 = MD5.getMD5(link.getBytes());

                                        runOnUiThread(new DataInsert(item));
                        }
                    }
                    eventType = xpp.next();
                }
            } catch (Exception e) {
                Log.i(" RssReaderView ", e.getMessage());
                e.printStackTrace();
            }
于 2012-09-18T09:59:29.337 回答
1

这是从 xml 解析的示例代码。首先你创建一个数据库来存储来自 xml 解析的数据......试试吧..

dh.delete(Exampl.TABLE, null, null);
    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (istream);
    doc.getDocumentElement ().normalize ();
    System.out.println ("Root element of the doc is " + 
         doc.getDocumentElement().getNodeName());
    NodeList dblist = doc.getElementsByTagName("database");
    Element e = (Element) dblist.item(0);
    NodeList tab = e.getElementsByTagName("table");
    System.out.println(tab.getLength() + " Tabels");

    for(int k=0;k<tab.getLength();k++) {

        Element el = (Element) tab.item(k);
        NodeList col = el.getElementsByTagName("column");

        System.out.println("ID is " );
        System.out.println();
        System.out.println(el.getElementsByTagName("column").item(0).getTextContent());
        System.out.println(el.getElementsByTagName("column").item(1).getTextContent());

        Category .add(el.getElementsByTagName("column").item(0).getTextContent());
        subCategory .add(el.getElementsByTagName("column").item(1).getTextContent());


    }


}catch (Exception err) {
    err.printStackTrace();
}

    for (int j = 0; j < (Category .size()); j++) {
        ContentValues questionValues = new ContentValues();
        System.out.println(Category .get(j));
        questionValues.put("Category ", Category .get(j));
        questionValues.put("subCategory ", subCategory .get(j));


        dh.insert(Example.TABLE, null,
                questionValues);

    }


}
于 2012-09-18T10:17:33.357 回答
0

我有同样的问题,我使用 XMLPullParser 做到了。您可以逐个解析 xml 并将它们存储到 hashmap 并且如果出现任何相同的标签,您可以将它们存储在向量中

于 2012-09-18T09:51:48.110 回答
0

使用这个检查

public class MyXmlHandler extends DefaultHandler{

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        if(qName.equalsIgnoreCase("Category")){ 
                     // do something
            String id = attributes.getValue("id")));
String name = attributes.getValue("Name")));
String subcategories = attributes.getValue("subcategories")));

        }else if(qName.equalsIgnoreCase("SubCategory")){
              // do something
            String id = attributes.getValue("id")));
String name = attributes.getValue("Name")));
String subcategories = attributes.getValue("subcategories")));
        }else if(qName.equalsIgnoreCase("ChildCategory")){
              // do something
            String id = attributes.getValue("id")));
String name = attributes.getValue("Name")));
String subcategories = attributes.getValue("subcategories")));
        }

    }


    public void endElement(String uri, String localName, String qName)
    throws SAXException {
        if(qName.equalsIgnoreCase("Category ")){
            //Do something
        }if(qName.equalsIgnoreCase("subCategory ")){
            //Do something
        }
if(qName.equalsIgnoreCase("ChildCategory ")){
            //Do something
        }
    }
    /* (non-Javadoc)
     * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
     */
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
    }

}
于 2012-09-18T10:01:27.527 回答
0

试试这个

     public class MyXmlHandler extends DefaultHandler{


 boolean isCategory, isChildCategory,isSubCategory = false;

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        if(qName.equalsIgnoreCase("Category"))
            {
            isCategory = true;
            String id = attributes.getValue("id");

        }else if(qName.equalsIgnoreCase("SubCategory"){ 
                     isSubCategory =true;
            String id = attributes.getValue("id");


        }else if(qName.equalsIgnoreCase("ChildCategory")){
              // do something
            String id = attributes.getValue("id");
            isChildCategory =false;
            }


    }


    public void endElement(String uri, String localName, String qName)
    throws SAXException {
        if(qName.equalsIgnoreCase("Category ")){
           isCategory = false;
        }if(qName.equalsIgnoreCase("subCategory ")){
            isSubCategory = false;
        }
if(qName.equalsIgnoreCase("ChildCategory ")){
            isChildCategory =false;
        }
    }
    /* (non-Javadoc)
     * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
     */
    public void characters(char[] ch, int start, int length)
            throws SAXException {
            String value = new String(ch,start,length);
        if(isCategory)
        {
          String str = value;
        }

        if(isSubCategory)
        {
          String str1 = value;
        }
    }

}
////////
 //TO call MyXmlHandler
 try{
            SAXParserFactory spf=SAXParserFactory.newInstance();
            SAXParser sp=spf.newSAXParser();
            XMLReader xr=sp.getXMLReader();
            MyXmlHandler datahandler=new MyXmlHandler();
            xr.setContentHandler(datahandler);


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

            }catch(Exception e)
            {
               Log.e("SAX XML", "i solve error");
            }
于 2012-09-18T10:28:16.653 回答
-1

您可以使用简单的 XML 解析器库,它很容易在 android 中使用。您只需在代码中创建相关的类和对象即可。您可以点击链接了解它 http://robertmassaioli.wordpress.com/2011 /04/21/simple-xml-in-android-1-5-and-up/

于 2012-09-21T10:31:52.417 回答