【问题标题】:How to parse complex xml data如何解析复杂的xml数据
【发布时间】:2012-09-18 09:48:17
【问题描述】:

大家好,我对 xml 解析有疑问,我有以下 xml 必须解析,但我很困惑如何解析它。我有 folow this

<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>

如果有解决方案请给我建议。

【问题讨论】:

    标签: android xml-parsing


    【解决方案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);
    
        }
    
    
    }
    

    【讨论】:

      【解决方案2】:

      使用 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();
                  }
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          用这个检查

          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
              }
          
          }
          

          【讨论】:

          • 谢谢阿莎,其实我不知道 xmlpullparser 所以你能告诉我如何实现这个
          【解决方案5】:

          试试这个

               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");
                      }
          

          【讨论】:

            【解决方案6】:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多