我只需要使用 java 读取 XML 文件中单个属性的值。 XML 看起来像这样:
<behavior name="Fred" version="2.0" ....>
我只需要读出版本。有人可以指出可以告诉我如何执行此操作的资源方向吗?
最佳答案
您不需要花哨的库 -- DOM 的普通旧 JAXP 版本和 XPath为此很容易阅读和写作。无论您做什么,都不要使用正则表达式。
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
public class GetVersion {
public static void main(String[] args) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse("file:////tmp/whatever.xml");
String version = xpath.evaluate("//behavior/@version", doc);
System.out.println(version);
}
}
关于java - 在java中查找XML文件中特定属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1330456/