2012-01-12 72 views
0

我试图通过SAX解析XML页面的technique.The结构解析从XML页面数据解析是的Android萨克斯XML与多个父

<?xml version="1.0" encoding="UTF-8"?> 
<news_magazine> 
    <latest_news> 
     <news> 
      <category_id>5</category_id> 
      <author>Super Admin</author> 
     </news> 
     <news> 
      <category_id>6</category_id> 
      <author>user</author> 
     </news> 
    </latest_news> 
    <categories> 
     <category> 
      <category_id>5</category_id> 
      <category_name>cricket</category_name> 
     </category> 
     <category> 
      <category_id>5</category_id> 
      <category_name>cricket</category_name> 
     </category> 
    </categories> 
</news_magazine> 

无论是新闻标签和类别标签包含类别ID。我怎样才能分别获得类别ID?

+0

看起来像XML是不正确的。请更新正确的XML。 – 2012-01-12 13:34:34

+0

@siva charan ....已更新 – sarath 2012-01-12 13:53:31

+1

考虑使用XML到对象的映射吗?手工构建解析器是乏味且容易出错的,请尝试类似..eh .. [pulloid](http://code.google.com/p/pulloid/)等。 – Jens 2012-01-12 14:01:06

回答

1

嘿,你可以用非常简单的方法做到这一点。只要在获取任何“新闻”或“类别”标记而不是在current_parent中分配条件时,在解析器中添加条件时,请保留一个额外变量 。 和比较标签“CATEGORY_ID”比current_parent也把状态时

public static String current_parent; 
public void startElement(String namespaceURI, String localName, 
      String qName, Attributes atts) { 
    if (localName.equals("news") { 
      current_parent = "news"; 
     // Do your code with news. 
     return; 
    } 
    else if (localName.equals("category") { 
      current_parent = "category"; 
     // Do your code with category. 
     return; 
    } 
    else if (localName.equals("category_id") { 
     if(current_parent.equals("category") 
      { 
     // Do your code with category's category_id. 
      }else if(current_parent.equals("news") 
       { 
     // Do your code with news's category_id. 
      } 
     return; 
    } 
} 
+0

...谢谢..我检查 – sarath 2012-01-12 14:04:14

+0

感谢Shashank Agarwal ...... – sarath 2012-01-12 14:47:06

1

考虑使用你所选择的数据绑定和拉解析器。这个任务对于(比如说)xstream或者jackson来说不​​会那么简单。如果你真的想手动执行,使用拉解析器 (你不再接收回调,但主动拉元素) - 这适应更好的Java程序流程