使用SAX的Java处理XML [英] Java handling XML using SAX

查看:89
本文介绍了使用SAX的Java处理XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的XML需要解析与给定结构:

I've got XML I need to parse with the given structure:

<?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解析器解析它:

I use SAX parser to parse it:

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) {
                /*---------------*/
            }
        });

我想第二个阅读标签元素属性(卷标1 和 LABEL2 ),但我的StartElementListener读第一标签,因为它们具有相同的结构和属性(那些标签=idAd标签=idNumPage)区分它们。我该如何告诉StartElementListener处理仅次于&LT;标签&GT; 元素

I want to read second "tag" element attributes(label1 and label2), but my StartElementListener reads first tag, because they have the same structure and attributes(those label="idAd" and label="idNumPage") distinguish them. How do I tell StartElementListener to process only second <tag> element?

推荐答案

如果你被卡住了 StartElementListener -way,你应该设置一个监听器标记元素,当它的标签等于idNumPage设置一个标志,让其他 StartElementListener 你的孩子元素应该读设置。

If you are stuck with the StartElementListener-way, you should set a listener to the tag element, and when it's label equals "idNumPage" set a flag, so the other StartElementListener you've set on the child element should be read.

更新
下面是如何利用这些监听器要做到这一点的例子:

Update
Below is a sample of how to do this using these listeners:

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 吸气实现,让我们知道什么时候读孩子标签的属性:

And the StartTagElementListener is implemented with an extra readNow getter, to let us know when to read the child tag's attributes:

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 :你有没有考虑使用 org.xml.sax.helpers.DefaultHandler中执行这个任务?

PS: Did you consider using a org.xml.sax.helpers.DefaultHandler implementation for this task?

这篇关于使用SAX的Java处理XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆