如何使用Java从xml文件读取属性? [英] How to read properties from xml file with java?

查看:98
本文介绍了如何使用Java从xml文件读取属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下xml文件:

<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-configuration 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文件读取属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆