How to get the value of a specific XML tag using StaX [duplicate]

妖精的绣舞 提交于 2019-12-06 14:25:22

You could do the following:

StreamSource xml = new StreamSource("input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
xsr.nextTag();
while(!xsr.getLocalName().equals("gender")) {
    xsr.nextTag();
}

XPath APIs

You could also use the javax.xml.xpath APIs:

package forum12062255;

import java.io.StringReader;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;

public class XPathDemo {

    private static final String XML = "<dennis><hair>brown</hair><pants>blue</pants><gender>male</gender></dennis>";

    public static void main(String[] args) throws Exception {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xPath = xpf.newXPath();

        InputSource inputSource = new InputSource(new StringReader(XML));
        String result = (String) xPath.evaluate("//gender", inputSource, XPathConstants.STRING);
        System.out.println(result);
    }

}
tkachuko

Guitarroka.

When I started my studying of XML parsing with Java I have followed this tutorial.

Using STaX you will need something like this (won't post full code list):

 if (event.asStartElement().getName().getLocalPart().equals("gender"))

If you insist on getting one specific tag value, you should look through DOM parser, it builds a tree from XML document, so you will be able to access element "gender" (examples of DOM are listed in link below). Good

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!