如何使用带有Java Stream实现Stax的xpath将元素添加到XML中

时间:2017-05-18 15:27:20

标签: java xml xpath stax

我正在尝试创建一种新方法来查找XML中的元素,我想在xml中创建dinamic查询,我没有找到使用xpath的示例,

可以将xpath与stax一起使用吗?如果没有,是否有一种简单的方法来创建查询以查找带有stax的元素?

public static void main(String[] args) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();

    Reader fileReader = new StringReader(ExempleXml.xml);
    XMLStreamReader reader = factory.createXMLStreamReader(fileReader);

    while (reader.hasNext()) {
        process(reader);
        reader.next();
    }

}

private static void process(XMLStreamReader reader) {
    int eventType = reader.getEventType();
    switch (eventType) {
        case XMLStreamConstants.START_ELEMENT:
            System.out.println("Start element: " + reader.getLocalName());

            int count = reader.getAttributeCount();
            for (int i = 0; i < count; i++) {
                String name = reader.getAttributeLocalName(i);
                String value = reader.getAttributeValue(i);
                System.out.println("\tAttribute name/value: " + name + "/" + value);
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            System.out.println("End element: " + reader.getLocalName());
            break;

        case XMLStreamConstants.CHARACTERS:
            System.out.println("Text: " + reader.getText());
            break;
        default:
            break;
    }
}

1 个答案:

答案 0 :(得分:1)

对于StaX解析器顶部的有限xpath支持,您可以使用 https://github.com/polyglotted/xpath-stax