2

我有大量复杂的 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 数据中读取第二个学生的姓名

例如.. 学生/学生/姓名[2]:Vinodh

4

0 回答 0