SAX解析-获取文本节点的有效方法 [英] SAX parsing - efficient way to get text nodes

查看:79
本文介绍了SAX解析-获取文本节点的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此XML代码段

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>

在SAX中,很容易获得属性值:

In SAX, it is easy to get attribute values:

@Override
public void startElement (String uri, String localName,
              String qName, Attributes attributes) throws SAXException{
    if(qName.equals("book")){
        String bookId = attributes.getValue("id");
        ...
    }
}

但是要获取文本节点的值,例如< author> 标记的值,这很难...

But to get the value of a text node, e.g. the value of the <author> tag, it is quite hard...

private StringBuffer curCharValue = new StringBuffer(1024);

@Override
public void startElement (String uri, String localName,
              String qName, Attributes attributes) throws SAXException {
    if(qName.equals("author")){
        curCharValue.clear();
    }
}

@Override
public void characters (char ch[], int start, int length) throws SAXException
{
     //already synchronized
    curCharValue.append(char, start, length);
}

@Override
public void endElement (String uri, String localName, String qName)
throws SAXException
{
    if(qName.equals("author")){
        String author = curCharValue.toString();
    }
}

  1. 我不确定上面的示例是否还能正常工作,您如何看待这种方法?
  2. 有没有更好的方法?(以获取文本节点的值)

推荐答案

这是使用SAX的常用方法.

That's the usual way to do it with SAX.

请注意,每个标签可能多次调用 characters().有关更多信息,请参见此问题.这是完整的示例.

Just beware that characters() may be called more than once per tag. See this question for more info. Here is a complete example.

否则,您可以尝试 StAX .

这篇关于SAX解析-获取文本节点的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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