读取 XML 的元素时出现异常

Getting exception while reading element for XML

我能够使用以下代码成功加载基于 XML 的 属性 文件:

    Properties props = new Properties();
    InputStream is = SampleConfig.class.getResourceAsStream("/test.properties");
    System.out.println(is);
    props.loadFromXML(is);
    String appId = props.getProperty("favoriteSeason");
    System.out.println(appId);

我的属性文件代码

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="favoriteSeason">test</entry>
<entry key="favoriteFruit">test1</entry>
<entry key="favoriteDay">test2</entry>
</properties>

但是,当我 运行 出现以下异常时:

Caused by: org.xml.sax.SAXParseException: The content of element type "properties" must match "(comment?,entry*)". at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source) at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) at org.apache.xerces.impl.dtd.XMLDTDValidator.handleEndElement(Unknown Source) at org.apache.xerces.impl.dtd.XMLDTDValidator.endElement(Unknown Source) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) at java.util.XMLUtils.getLoadingDoc(XMLUtils.java:113) at java.util.XMLUtils.load(XMLUtils.java:85)

您正在尝试使用 loadFromXML() 方法从 .properties 文件加载。我认为这是问题所在,因为堆栈跟踪显示它没有获得所需的评论输入类型格式。