Java XML 解析 [英] Java XML parsing
本文介绍了Java XML 解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要像这样从 XML 文件中提取(使用 Java)给定名称标签的标签:
I need to extract (using Java) the tag for the given name tag from XML file like this:
这是我的 XML 文件:
Here is my XML file:
<aa>
<bb>
<name>k1</name>
<value>5</value>
</bb>
<bb>
<name>k2</name>
<value>7</value>
</bb>
</aa>
函数的输入:
(此示例的输出应返回 7
)
还有更高级的问题:我需要从 XML 文件中提取所有名称:值对,然后名称由正则表达式给出我认为 XPath 是这里的正确工具,但在细节上是魔鬼.
Also more advanced question: I need to extract all name:value pairs from the XML file then the name is given by regular expression I am thinking that XPath is the right tool here, but devil in details.
推荐答案
您可以使用作为 Java SE 5 一部分包含的 javax.xml.xpath API:
You can use the javax.xml.xpath APIs that are included as part of Java SE 5:
import java.io.FileReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class Demo {
public static void main(String[] args) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression xpe = xpath.compile("//bb[name/text()='k2']/value");
InputSource xml = new InputSource(new FileReader("input.xml"));
String result = xpe.evaluate(xml);
System.out.println(result);
}
}
这篇关于Java XML 解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文