簡體   English   中英

如何使用java從xml文件中讀取屬性?

[英]How to read properties from xml file with java?

我有以下 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 做這樣的事情:

Xml xml = new Xml("my.xml");
Resource res001 = xml.getResouceById("res003");
System.out.println("propF: " + res.getProperty("propF"));

所以它打印:

F

我已經嘗試過使用 XPathExpressionEngine 的 apache commons-configurations XMLConfiguration,但我無法讓它工作。 我用谷歌搜索並找到了一些例子,但都不起作用:(我正在尋找一個不需要遍歷所有元素的解決方案。

問候,亞歷克斯

這很簡單,假設您願意將屬性文件重新編寫為標准 Java 格式。 假設您在名為props.xml的文件中有以下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>

然后從文件中讀取屬性,如下所示:

java.util.Properties prop = new Properties();
prop.loadFromXML(new FileInputStream("props.xml"));
System.out.println(prop.getProperty("propF"));

我只是使用 JAXB 將數據綁定到具有類似於 XML 文檔結構的對象集。

就像是:

@XmlRootElement("resources")
public class Resources {
  public List<Resource> resource = new ArrayList<Resource>(); // important, can't be left null
}
public class Resource {
  @XmlAttribute public String id;
  public List<Property> property;
}
// and so on

一個可能的問題是關於列表序列化; 有兩種模式,wrapped 和 unwrapped; 在你的情況下,你想要“解開”。 注釋的 Javadocs 應該顯示注釋來定義它。

有很多方法。 一種是做JDOM和xpath。 像這樣(來自這篇文章: http : //onjava.com/onjava/2005/01/12/xpath.html ):

SAXBuilder saxBuilder = 
    new SAXBuilder("org.apache.xerces.parsers.SAXParser");
org.jdom.Document jdomDocument =
    saxBuilder.build(new File("somefile");
org.jdom.Attribute levelNode = 
    (org.jdom.Attribute)(XPath.selectSingleNode(
        jdomDocument,
        "/resources/resource[@id='res003']/property[@name='propF']/@value"));
System.out.println(levelNode.getValue());

沒有測試它,但應該工作。 有關 xpath 教程,請參閱http://zvon.org/xxl/XPathTutorial/General/examples.html 它是最好和最快的教程。

如果經常調用,請注意 saxbuilder 生命周期。

感謝所有的答案/建議! 我嘗試了上面給出的一些 xml 庫,並決定使用Simple XML 庫。 我發現“字典”實用程序類特別有用,可以避免遍歷所有元素。 優雅而簡單:)

下面是我如何使用它。 我希望它可以幫助別人...

問候,

亞歷克斯

一個工作示例(在 Windows Vista 上):

package demo;

import java.io.File;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Demo {
    public static void main(String[] args) throws Exception {
        File file = new File("c:\\temp\\resources.xml");
        Serializer serializer = new Persister();
        Resources resources = serializer.read(Resources.class, file);

        Resource resource = resources.getResourceByName("res001");
        System.out.println(resource.getProperty("propA"));
        System.out.println(resource.getProperty("propB"));
    }
}

控制台窗口:

A-001
B-001

資源.java

package demo;

import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.util.Dictionary;

@Root(name="resources")
public class Resources {
    @ElementList(entry = "resource", inline = true) 
    private Dictionary<Resource> resources = new Dictionary<Resource>();

    public Resources(@ElementList(entry = "resource", inline = true) Dictionary<Resource> resources) {
        this.resources = resources;
}

    public Resource getResourceByName(String name){
        return resources.get(name);
    }
}

資源.java

package demo;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.util.Dictionary;
import org.simpleframework.xml.util.Entry;

public class Resource  implements Entry{
    @Attribute(name = "name") private final String name;
    @ElementList(inline=true, name="property") private Dictionary<Property> properties;

    public Resource(
                    @Attribute(name = "name") String name, 
                    @ElementList(inline=true, name="property") Dictionary<Property> properties) {
            this.name = name;
            this.properties = properties;
    }

    public String getName() {
        return name;
    }

    public String getProperty(String name) {
        return properties.get(name).getValue();
    }
}

屬性.java

package demo;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.util.Entry;

@Root
public class Property implements Entry{
    @Attribute(name="name") private String name;
    @Attribute(name="value") private String value;

    public Property(@Attribute(name="name") String name, @Attribute(name="value") String value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }
}

資源文件

<resources>
    <resource name="res001">
        <property name="propA" value="A-001" />
        <property name="propB" value="B-001" />
    </resource>
    <resource name="res002">
        <property name="propA" value="A-002" />
        <property name="propB" value="B-002" />
    </resource>
    <resource name="res003">
        <property name="propA" value="A-003" />
        <property name="propB" value="B-003" />
    </resource>
</resources>

您可以使用多種解析器。 對我來說,這些解析器工作正常:

我重新推薦了 XStream。

它解析具有相同結構的對象中的 XML。

關於XStream

您的對象將是:

List<Resources>

Resources具有屬性,帶有 setter 和 getter, id是一個具有屬性namevalue的對象Property

希望這有幫助

如果我是您,我會使用您想要的方法( getPropertyResource等)的接口並提供 XPath 實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM