【问题标题】:How to read properties from xml file with java?如何用java从xml文件中读取属性?
【发布时间】:2012-01-21 14:51:13
【问题描述】:

我有以下 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,但我就是无法让它工作。我用谷歌搜索并找到了一些例子,但都不起作用:( 我正在寻找一种不需要遍历所有元素的解决方案。

问候, 亚历克斯

【问题讨论】:

  • 有点跑题了,但是有什么特别的原因将您的属性存储为单个元素而不是属性? &lt;resource id="res003" propE="E" propF="F"/&gt;
  • 我不认识这种格式。这是什么?
  • Emil,这样感觉最自然。还有其他建议吗?

标签: java xml-parsing


【解决方案1】:

这很简单,假设您愿意将属性文件重写为标准 Java 格式。假设您在名为 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"));

【讨论】:

    【解决方案2】:

    感谢所有的答案/建议!我尝试了上面给出的一些 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;
        }
    }
    

    资源.xml

    <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>
    

    【讨论】:

      【解决方案3】:

      我只想使用 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
      

      一个可能的问题是关于列表序列化;有两种模式,包裹和展开;在你的情况下,你想要“解开”。注释的 Javadocs 应该显示注释来定义它。

      【讨论】:

      • 是的,但是先创建一个 XSD,然后生成 bean。jaxb.java.net/tutorial
      • 不,绝对不——如果需要 XSD,我宁愿做根管治疗。相反,您只需定义 POJO(使用 setter 和 getter;或公共字段)并使用它。不涉及架构。
      【解决方案4】:

      有很多方法。一种是做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 生命周期,请注意它。

      【讨论】:

        【解决方案5】:

        我重新设计了 XStream。

        它以相同的结构解析对象中的XML。

        关于XStream

        您的对象将是:

        List<Resources>
        

        而Resources具有属性,带有setter和getter,id是一个对象Property,带有name和value的属性。

        希望有帮助

        【讨论】:

          【解决方案6】:

          如果我是你,我会使用带有你想要的方法的接口(@98​​7654321@、Resource 等)并提供 XPath 实现。

          【讨论】:

            【解决方案7】:

            您可以使用多种解析器。对我来说,这些解析器运行良好:

            【讨论】:

              猜你喜欢
              • 2020-11-11
              • 1970-01-01
              • 1970-01-01
              • 2021-08-08
              • 1970-01-01
              • 2011-10-19
              • 2017-09-06
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多