SAX解析 – 获取文本节点的有效方法
鉴于此XML片段
Gambardella, Matthew
在SAX中,很容易获得属性值:
@Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException{ if(qName.equals("book")){ String bookId = attributes.getValue("id"); ... } }
但是为了获得文本节点的值,例如标签的值,这很难……
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(); } }
- 我不确定上面的样本是否正常工作,您如何看待这种方法?
- 有没有更好的办法? (获取文本节点的值)
这是使用SAX的常用方法。
请注意,每个标记可能会多次调用characters()
。 有关详细信息,请参阅此问题 。 这是一个完整的例子 。
否则你可以试试StAX 。
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 ? } }