如何用java从xml文件中读取属性?

How to read properties from xml file with java?(如何用java从xml文件中读取属性?)
本文介绍了如何用java从xml文件中读取属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)