How to get the value of a specific XML tag using S

2019-08-01 19:56发布

问题:

Possible Duplicate:
How to use StaX

Hey guys so I have an XML file and I want Java to spit out the value of a specific tag. For example here is my XML:

<?xml version="1.0"?>
    <dennis>
        <hair>brown</hair>
        <pants>blue</pants>
        <gender>male</gender>
    </dennis>

So let's say I want Java to spit out the value of "gender" is there code I could use like

XMLStreamReader.goToTag("gender");
System.out.println(XMLStreamReader.getLocalName());

回答1:

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);
    }

}


回答2:

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



标签: java xml tags stax