读取 XML 元素时出现异常

Posted

技术标签:

【中文标题】读取 XML 元素时出现异常【英文标题】:Getting exception while reading element for XML 【发布时间】:2016-01-11 07:47:39 【问题描述】:

我能够使用以下代码成功加载基于 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>

但是,当我运行它时,我得到以下异常:

原因:org.xml.sax.SAXParseException:元素类型“properties”的内容必须匹配“(comment?,entry*)”。 在 org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(未知来源) 在 org.apache.xerces.util.ErrorHandlerWrapper.error(未知来源) 在 org.apache.xerces.impl.XMLErrorReporter.reportError(未知来源) 在 org.apache.xerces.impl.XMLErrorReporter.reportError(未知来源) 在 org.apache.xerces.impl.dtd.XMLDTDValidator.handleEndElement(未知来源) 在 org.apache.xerces.impl.dtd.XMLDTDValidator.endElement(未知来源) 在 org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(未知来源) 在 org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(未知来源) 在 org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(未知来源) 在 org.apache.xerces.parsers.XML11Configuration.parse(未知来源) 在 org.apache.xerces.parsers.XML11Configuration.parse(未知来源) 在 org.apache.xerces.parsers.XMLParser.parse(未知来源) 在 org.apache.xerces.parsers.DOMParser.parse(未知来源) 在 org.apache.xerces.jaxp.DocumentBuilderImpl.parse(未知来源) 在 java.util.XMLUtils.getLoadingDoc(XMLUtils.java:113) 在 java.util.XMLUtils.load(XMLUtils.java:85)

【问题讨论】:

为我工作,输出为:java.io.BufferedInputStream@3a09a47d test 感谢回复,其实问题出在 loadFromXML() 方法上 【参考方案1】:

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

【讨论】:

以上是关于读取 XML 元素时出现异常的主要内容,如果未能解决你的问题,请参考以下文章

在 Java 中读取 protobuf 消息时出现异常

通过 AudioSystem.getAudioInputStream(file) 读取 MP3 文件时出现异常

在 GCS 上读取 Avro 文件时出现 OutOfMemoryError 异常

读取 xml 时出现地址越界错误

AWS ECS Blue/Green CodePipeline:尝试读取图像工件时出现异常

net.jpounz.lz4 使用火花流从 kafka 读取时出现异常