如何使用 StaX 获取特定 XML 标记的值 [英] How to get the value of a specific XML tag using StaX
本文介绍了如何使用 StaX 获取特定 XML 标记的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
如何使用 StaX
大家好,我有一个 XML 文件,我希望 Java 吐出特定标签的值.例如,这是我的 XML:
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>
所以假设我想让 Java 吐出性别"的值是否有我可以使用的代码
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());
推荐答案
您可以执行以下操作:
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:
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);
}
}
这篇关于如何使用 StaX 获取特定 XML 标记的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文