我正在尝试将 xml 文件(作为 byte[]
)绑定(bind)到 java 对象。这是我的代码-
public voidinputConfigXML(String xmlfile, byte[] xmlData) {
IBindingFactory bFact = BindingDirectory.getFactory(GroupsDTO.class);
IUnmarshallingContext uctx = bFact.createUnmarshallingContext();
groups = (GroupsDTO) uctx.unmarshalDocument(new ByteArrayInputStream(xmlData), "UTF8");
}
unmarshalDocument()
给了我这个异常。我该怎么办?
仅供引用:作为 JUnit 测试用例运行
以下是堆栈跟踪 -
Error parsing document (line 1, col 1)
org.xmlpull.v1.XmlPullParserException: only whitespace content allowed before start tag and not \u0 (position: START_DOCUMENT seen \u0... @1:1)
at org.xmlpull.mxp1.MXParser.parseProlog(MXParser.java:1519)
at org.xmlpull.mxp1.MXParser.nextImpl(MXParser.java:1395)
at org.xmlpull.mxp1.MXParser.next(MXParser.java:1093)
at org.jibx.runtime.impl.XMLPullReaderFactory$XMLPullReader.next(XMLPullReaderFactory.java:291)
at org.jibx.runtime.impl.UnmarshallingContext.toStart(UnmarshallingContext.java:451)
at org.jibx.runtime.impl.UnmarshallingContext.unmarshalElement(UnmarshallingContext.java:2755)
at org.jibx.runtime.impl.UnmarshallingContext.unmarshalDocument(UnmarshallingContext.java:2905)
at abc.dra.DRAAPI.inputConfigXML(DRAAPI.java:31)
at abc.dra.XMLToObject_Test.test(XMLToObject_Test.java:34)
[...]
这是我形成 byte[]-的代码
void test() {
String xmlfile = "output.xml"
File file = new File(xmlfile);
byte[] xmlData = new byte[(int) file.length()];
groups = dra.inputConfigXML(xmlfile, xmlData);
}
最佳答案
ByteArrayInputstream 为空:
only whitespace content allowed before start tag and not \u0
(position: START_DOCUMENT seen \u0... @1:1)
意味着,\u0 位被发现作为 XML 中的第一个字符。
确保您的 byte[]
中有内容,并且 UTF-8 不以 BOM 开头。
我不认为BOM是你的问题,但我经常遇到关于BOM和java的问题。
更新
您没有填充byte[]
。您必须将文件内容读入byte[]
:
读这个:File to byte[] in Java
顺便说一句:byte[] xmlData = new byte[(int) file.length()];
是不好的代码风格,因为您会遇到较大的 XML 文件的问题。如果它们大于 Integer.MAX_VALUE
,您将读取损坏的文件。
关于java - org.xmlpull.v1.XmlPullParserException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10683363/