2011-04-30 38 views
1

我有XML我需要给定的结构解析:的Java处理XML使用SAX

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <tag label="idAd"> 
    <child label="text">Text</child> 
    </tag> 
    <tag label="idNumPage"> 
    <child label1="text" label2="text">Text</child> 
    </tag> 
</root> 

我用SAX解析器解析它:

RootElement root=new RootElement("root"); 
android.sax.Element page_info=root.getChild("tag").getChild("child"); 
page_info.setStartElementListener(new StartElementListener() { 

      @Override 
      public void start(Attributes attributes) { 
       /*---------------*/ 
      } 
     }); 

我想第二读“标签“元素属性(label1label2),但我的StartElementListener读取第一个标签,因为它们具有相同的结构和属性(那些label="idAd"label="idNumPage")可以区分它们。我如何告诉StartElementListener只处理第二个<tag>元素?

+0

只是要清楚:你使用的不是SAX,它是一些在SAX之上分层的特定于android的类。我只是提到这一点,因为任何知道SAX并且不知道android(像我一样)的人都会被你的问题困惑。 – 2011-04-30 22:05:13

+0

我想说,如果你在Android上使用XML,那么你真的应该使用Simple XML(http://simple.sourceforge.net/)。我有一篇博客文章解释了如何整合到您的项目中:http://massaioli.homelinux.com/wordpress/2011/04/21/simple-xml-in-android-1-5-and-up/ – 2011-05-01 02:21:10

回答

1

如果你被卡住的StartElementListener三通,你应该监听器设置为tag元素,当它label等于“idNumPage”设置一个标志,因此其他StartElementListener你的child元素上设置应读。

更新
下面是如何做到这一点使用这些听众的样本:

android.sax.Element tag = root.getChild("tag"); 
final StartTagElementListener listener = new StartTagElementListener(); 
tag.setStartElementListener(listener); 

android.sax.Element page_info = tag.getChild("child"); 
page_info.setStartElementListener(new StartElementListener() 
{ 
    @Override 
    public void start(Attributes attributes) 
    { 
     if (listener.readNow()) 
     { 
      //TODO: you are in the tag with label="idNumPage" 
     } 
    } 
}); 

而且StartTagElementListener与额外readNow吸气实现,让我们知道什么时候读child标签的属性:

public final class StartTagElementListener implements StartElementListener 
{ 
    private boolean doReadNow = false; 

    @Override 
    public void start(Attributes attributes) 
    { 
     doReadNow = attributes.getValue("label").equals("idNumPage"); 
    } 

    public boolean readNow() 
    { 
     return doReadNow; 
    } 
} 

PS:你有没有CON sider使用org.xml.sax.helpers.DefaultHandler执行这个任务?

+0

Now我使用匿名内部类作为每个标记的侦听器,我认为它不是有效的,所以我考虑使用DefaultHandler。 – 2011-05-01 07:39:19

+0

(匿名)内部类没有问题,但在这种情况下,'DefaultHandler'实现是更好的选择,我很高兴你做到了! – rekaszeru 2011-05-01 08:55:45