【问题标题】:SAX parsing - efficient way to get text nodesSAX 解析 - 获取文本节点的有效方法
【发布时间】:2011-01-05 02:24:31
【问题描述】:

鉴于此 XML sn-p

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

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

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

但是要获取文本节点的值,例如&lt;author&gt;标签的值,挺难的……

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. 有没有更好的方法? (获取文本节点的值)

【问题讨论】:

  • 这是我认为效率最高的...

标签: java xml sax


【解决方案1】:
public void startElement(String strNamespaceURI, String strLocalName,
      String strQName, Attributes al) throws SAXException {
       if(strLocalName.equalsIgnoreCase("HIT"))
       {
            String output1 = al.getValue("NAME");
          //this will work but how can we parse if NAME="abc" only     ?
       }

   }

【讨论】:

    【解决方案2】:

    这是使用 SAX 的常用方法。

    请注意,characters() 可能会在每个标签中多次调用。请参阅此question 了解更多信息。这是一个完整的example

    否则你可以试试StAX

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 2012-12-26
      • 2011-09-25
      • 2015-11-10
      • 2011-05-16
      • 2014-11-15
      • 2012-11-10
      相关资源
      最近更新 更多