您可以执行以下操作:
StreamSource xml = new StreamSource("input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
xsr.nextTag();
while(!xsr.getLocalName().equals("gender")) {
xsr.nextTag();
}
XPath API
您还可以使用javax.xml.xpath
API:
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);
}
}