在Java中从xml获取值到.properties文件

时间:2012-06-29 09:10:51

标签: java xml properties

我在.xml文件中有与数据库连接相关的属性。我想在.properties文件中使用相同的值。是否可以从.xml文件中获取值并设置为.properties?

- 感谢

使用 loadFromXML

时出现例外情况

线程“main”中的异常java.util.InvalidPropertiesFormatException:org.xml.sax.SAXException:无效的系统标识符:http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd     在java.util.XMLUtils.load(XMLUtils.java:76)     at java.util.Properties.loadFromXML(Properties.java:868)     at com.generalsentiment.test.quartz.CronTriggerExample.run(CronTriggerExample.java:40)     at com.generalsentiment.test.quartz.CronTriggerExample.main(CronTriggerExample.java:117) 原因:org.xml.sax.SAXException:无效的系统标识符:http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd     at java.util.XMLUtils $ Resolver.resolveEntity(XMLUtils.java:190)     at org.apache.xerces.util.EntityResolverWrapper.resolveEntity(Unknown Source)     at org.apache.xerces.impl.XMLEntityManager.resolveEntity(Unknown Source)     at org.apache.xerces.impl.XMLDocumentScannerImpl $ DTDDispatcher.dispatch(Unknown Source)     at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)     在org.apache.xerces.parsers.XML11Configuration.parse(未知来源)     在org.apache.xerces.parsers.DTDConfiguration.parse(未知来源)     在org.apache.xerces.parsers.XMLParser.parse(未知来源)     在org.apache.xerces.parsers.DOMParser.parse(未知来源)     在org.apache.xerces.jaxp.DocumentBuilderImpl.parse(未知来源)     at java.util.XMLUtils.getLoadingDoc(XMLUtils.java:102)     在java.util.XMLUtils.load(XMLUtils.java:74)     ......还有3个 Java结果:1

2 个答案:

答案 0 :(得分:1)

将努力使用.properties文件中的值创建XML属性文件。这里没有指定XML的模式;因此假设它不是Java XML属性格式。

Java XML属性文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Hi</comment>
<entry key="foo">bar</entry>
<entry key="fu">baz</entry>
</properties>

Java代码:

import java.util.*;
import java.io.*;

public class LoadSampleXML {
  public static void main(String args[]) throws Exception {
    Properties prop = new Properties();
    FileInputStream fis =
      new FileInputStream("sampleprops.xml");
    prop.loadFromXML(fis);
    prop.list(System.out);
    System.out.println("\nThe foo property: " +
        prop.getProperty("foo"));
  }
}

here引用的示例代码。

答案 1 :(得分:1)

您是否检查了属性的javadocs。 有一个loadFromXML方法就是这样做的。 唯一的限制是XML文件确认了一个特定的结构,并且应该有如下所述的DOCTYPE声明。

<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">