问题描述
我有以下 xml 文件:
I have the following xml file:
<resources>
<resource id="res001">
<property name="propA" value="A" />
<property name="propB" value="B" />
</resource>
<resource id="res002">
<property name="propC" value="C" />
<property name="propD" value="D" />
</resource>
<resource id="res003">
<property name="propE" value="E" />
<property name="propF" value="F" />
</resource>
</resources>
我怎样才能用 Java/Xml 做这样的事情:
How can I do something like this with Java/Xml:
Xml xml = new Xml("my.xml");
Resource res001 = xml.getResouceById("res003");
System.out.println("propF: " + res.getProperty("propF"));
所以它打印出来:
F
我已经用 XPathExpressionEngine 尝试了 apache commons-configurations XMLConfiguration,但我就是不能让它工作.我用谷歌搜索并找到了一些例子,但都不起作用:(我正在寻找一种不需要遍历所有元素的解决方案.
I have tried apache commons-configurations XMLConfiguration with XPathExpressionEngine, but I just can't make it work. I have googled and found some examples, but neither would work :( I'm looking for a solution where I don't need to loop through all the elements.
问候,亚历克斯
推荐答案
这很简单,假设您愿意将属性文件重写为标准 Java 格式.假设您在名为 props.xml
的文件中有以下内容:
This is trivial, assuming you're willing to re-write your properties file into the standard Java format. Assume you have the following in a file called props.xml
:
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>This is a comment</comment>
<entry key="propA">A</entry>
<entry key="propB">B</entry>
<entry key="propC">C</entry>
<entry key="propD">D</entry>
<entry key="propE">E</entry>
<entry key="propF">F</entry>
</properties>
然后像这样从文件中读取属性:
Then read properties from the file like this:
java.util.Properties prop = new Properties();
prop.loadFromXML(new FileInputStream("props.xml"));
System.out.println(prop.getProperty("propF"));
这篇关于如何用java从xml文件中读取属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!