我有大而复杂的XML数据来过滤源数据中的特定标记。我正在使用stax解析器,但我无法从特定路径获取值。我读了许多文章,stax解析器不支持XPath。请给我一些使用Stax解析器实现XPath概念的替代方法。我是这个Stax解析器的新手。
代码:
package verizon.npo.util.xmltester;
import java.io.StringReader;
import javax.xml.stream.Location;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
public class StAXAPIEvent {
public static void main(String[] args) {
XMLInputFactory factory;
XMLEventReader reader;
String xml =
"<STUDENTS>" +
" <STUDENT>"+
" <NAME>Karthick</NAME>" +
" <NAME>Vinodh</NAME>" +
" <NAME>Deva</NAME>" +
" </STUDENT>"+
"</STUDENTS>";
try {
factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,
Boolean.TRUE);
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,
Boolean.FALSE);
event
factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
reader = factory.createXMLEventReader(new StringReader(xml));
XMLStreamReader xsr = factory.createXMLStreamReader(new StringReader(xml));
Location loc = null;
while (reader.hasNext()) {
//returns the event type
XMLEvent e = reader.nextEvent();
if (e.isStartElement()) {
StartElement startElement = e.asStartElement();
System.out.println("Start element :
"+startElement.getName().getLocalPart());
}
if (e.isCharacters()) {
System.out.println("Characters : "+e.asCharacters().getData());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
我想从这个xml数据中读取第二个学生的名字
ex ..学生/学生/姓名[2]:Vinodh