0

我正在尝试在我的 android 应用程序中解析一个非常简单的 XML,例如:

<data> 
    <section id="123">bla</section> 
    <area>blabla</area> 
</data> 

但是在每个示例中,当我需要提取的是显示的数据 - “bla”和“blabla”时,我发现如何提取属性中的数据(id 为 123)。
如何使用 SAXParser 做到这一点?

4

4 回答 4

0

解析器处理程序中的characters方法负责处理元素的文本值。

于 2012-05-26T19:20:14.547 回答
0

您需要覆盖characters方法。

于 2012-05-26T19:21:06.040 回答
0

教程准确地回应你想要的希望你会喜欢

查看解析器处理程序中的 characters 方法如何处理提取元素的文本值

于 2012-05-26T19:37:07.360 回答
0

好吧,手工编写解析器当然很有趣且容易出错,但是我建议使用框架——即使是像内置android.sax包这样的简单框架。

使用StartElementListener(如果你想要属性的话)& EndTextListener(捕获元素的正文):

class Section implements StartElementListener, EndTextElementListener {
    String mValue;
    String mId;
    @Override
    public void end(String body) {
        mValue = body;
    }
    @Override
    public void start(Attributes attributes) {
        mId = attributes.getValue("", "id");
    }
}

这些类型的侦听器附加到Element从 a 派生的 s上RootElement,如下所示:

Section section = new Section();
RootElement data = new RootElement("data");
// Use "requireChild" if a "section" is required as a child of "data".
Element s = data.getChild("section");
s.setStartElementListener(section);
s.setEndTextElementListener(section);
try {
    Xml.parse(xml, data.getContentHandler());
} catch (SAXException e) {
}

基本上,这可以帮助您为 SAX 构建内容处理程序,该处理程序关心层次结构并轻松跟踪您正在解析的元素。我猜也是简短而漂亮的代码。

于 2012-05-26T20:06:31.833 回答