8

鉴于此 XML 片段

<?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");
        ...
    }
}

但是要获得一个文本节点的值,例如<author>标签的值,这是相当困难的......

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

2 回答 2

9

这是使用 SAX 执行此操作的常用方法。

请注意,characters()每个标签可能会多次调用它。有关更多信息,请参阅此问题。这是一个完整的例子

否则你可以试试StAX

于 2010-01-14T14:36:54.577 回答
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     ?
       }

   }
于 2011-09-16T13:12:42.610 回答