我尝试解析xml收到以下错误: “意外令牌错误”
这里是myxml文件
<?xml version="1.0" encoding="utf-8"?>
<records>
<record date="11/12">
<profile>
<name>john</name>
<sex>male</sex>
<age>18</age>
</profile>
<profile>
<name>bill</name>
<sex>male</sex>
<age>20</age>
</profile>
<profile>
<name>jully</name>
<sex>female</sex>
<age>22</age>
</profile>
</record>
</records>
和xml解析代码
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(new InputStreamReader(ist, "UTF-8")));
xml文件错了?要么... 帮助将不胜感激
答案 0 :(得分:0)
它也可能取决于解析器。我认为存在相关问题KXmlParser throws "Unexpected token" exception at the start of RSS pasing:
引用vmironov的答案:
因此,一个原因可能是xml文件实际上并不以<?xml version="1.0" encoding="utf-8"?>.
开头。它以三个特殊字节EF BB BF
开头,Byte order mark。
InputStreamReader
(您在此处使用的)不会自动处理这些字节,因此您必须手动处理它们。最简单的方法是使用BOMInpustStream
库中的Commons IO
。
希望这会有所帮助。
答案 1 :(得分:0)
我认为您的XML文件非常好。
但是,如果xml在文件中...为什么不使用'InputSource'的'FileInputStream'内部?:
Document doc = db.parse(new FileInputStream(xmlFile) );
顺便说一下,我想把一个小小的应用程序放在这里,它可以做到你想要的并且不会崩溃。它在SDCArd中创建你的xml文件,然后它会成功地读取那个xml并构建'Document'对象:
package com.example.xmlt;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
public static String MYDIRECTORY = "MyDirectory";
public static String FILENAME = "file1.xml";
public static String XMLCONTENT =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
"<records>\n"+
"<record date=\"11/12\">\n"+
"<profile>\n"+
"<name>john</name>\n"+
"<sex>male</sex>\n"+
"<age>18</age>\n"+
"</profile>\n"+
"<profile>\n"+
"<name>bill</name>\n"+
"<sex>male</sex>\n"+
"<age>20</age>\n"+
"</profile>\n"+
"<profile>\n"+
"<name>jully</name>\n"+
"<sex>female</sex>\n"+
"<age>22</age>\n"+
"</profile>\n"+
"</record>\n"+
"</records>\n";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
File xmlFile = createFile(getApplicationContext(),FILENAME,XMLCONTENT);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(xmlFile) );
}catch(Exception e){
e.printStackTrace();
}
}
private static File createFile(Context context, String filename, String fileContent)
throws FileNotFoundException, IOException{
String baseDir = Environment.getExternalStorageDirectory().getPath();
File f1 = new File( baseDir+ "/"+ MYDIRECTORY +"/");
f1.mkdirs();
File f2 = new File( baseDir+ "/"+ MYDIRECTORY +"/" + filename);
FileOutputStream outputStream = new FileOutputStream(f2);
outputStream.write(fileContent.getBytes());
outputStream.close();
return f2;
}
}