Java解析来自UTF-16LE字符串的XML

Java解析来自UTF-16LE字符串的XML,java,android,xml,saxparser,utf-16,Java,Android,Xml,Saxparser,Utf 16,我试图解析嵌入文件中的UTF-16LE XML字符串。我能够将实际字符串读入字符串对象,并且可以在watch窗口中查看XML,看起来很好。问题是,当我尝试解析它时,会不断抛出异常。我尝试在getBytes行和InputStreamReader构造函数中指定UTF-16和UTF-16LE,但它仍然引发异常 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder bui

我试图解析嵌入文件中的UTF-16LE XML字符串。我能够将实际字符串读入字符串对象,并且可以在watch窗口中查看XML,看起来很好。问题是,当我尝试解析它时,会不断抛出异常。我尝试在getBytes行和InputStreamReader构造函数中指定UTF-16和UTF-16LE,但它仍然引发异常

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;

builder = builderFactory.newDocumentBuilder();      
Document document = null;
byte[] bytes = xmlString.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
InputSource is = new InputSource(new InputStreamReader(inputStream));
document = builder.parse(is); // throws SAXParseException
编辑:这是使用Android。另外,这里是我在堆栈跟踪顶部得到的异常:

12-18 13:51:12.978:W/System.err(5784):org.xml.sax.SAXParseException:应为名称(位置:java.io中的START_TAG@1:2)。InputStreamReader@4118c880) 12-18 13:51:12.978:W/System.err(5784):位于org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:146)
12-18 13:51:12.978:W/System.err(5784):在javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:107)

下面是我最后做的:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;

builder = builderFactory.newDocumentBuilder();      
Document document = null;
byte[] bytes = Charset.forName("UTF-16LE").encode(xmlString).array();
InputStream inputStream = new ByteArrayInputStream(bytes);
document = builder.parse(inputStream);

来源:

在同一程序中,不需要在字符串和字节之间来回转换。这就像:

String xml=“你好,世界!”;
Document dom=DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(新的InputSource(新的StringReader(xml));

什么是wrmHeaderXml?一个字符串,一个对象还是什么?看起来您正在从字节转换为字符,然后又从字符转换为字节。为什么?如果您已经获得了字节,只需将其输入到InputSource(InputStream),我猜它是一个字符串。如果您有一个String对象(并且您声明可以在控制台中查看它),那么内部编码并不重要,因为它是Java字符串,编码字符串的目的是什么?我只是调用了xmlString.getBytes并将其传递到ByteArrayInputStream,然后它会抛出SAXParseException。但是为什么需要从字符串中提取字节呢?只需将a传递给
InputSource
ctor,我尝试传递一个StringReader,但它仍然抛出异常。我认为这与编码有关。Java字符串没有任何关联的编码。这是一根绳子。在内部,它是用UTF-16LE存储的,但这对StringReader实现并不重要。这会在解析行上抛出一个SAXParseException。无需粗鲁。当我尝试对正在解析的XML使用上面的解析行时,它会抛出一个SAXParseException。我在上面张贴了堆栈顶部的跟踪。如果我只调用xmlString.getBytes()并查看二进制数据,它就是UTF-16LE编码。前两个字节是0xFF 0xFE,它告诉我这是little endian UTF-16编码。@rplankenhorn听起来像是您的
xmlString
实际上包含BOM作为其第一个字符。如果从字符串中去掉第一个字符,然后根据结果创建一个StringReader,那么它应该可以很好地从中解析出来,而不需要来回转换到字节。其他每个字符也是0x00,所以我不确定这是否有效。@rplankenhorn我需要粗鲁一点,因为你的态度不是SO用户的态度-你没有试图理解问题,你不理解我的答案,你甚至否决了它,这是不公平的,因为你不理解它,并在你的Android系统上抛出了一个例外(顺便说一句,堆栈跟踪是无用的,所以我的假设是正确的,你不知道如何读取堆栈跟踪-你也需要粘贴根本原因)。根据你的评论,输入字符串是问题所在,所以请告诉我你从何处获得它或如何构建它