我正在尝试用Java读取整个XML文件。以下是我的XML文件-
<?xml version="1.0" encoding="UTF-8"?>
<app hash='nv', name='Tech', package = '1.0', version='13', filesize='200', create_date='01-03-1987', upate_date='07-09-2013' >
<url>
<name>RJ</name>
<score>10</score>
</url>
<url>
<name>ABC</name>
<score>20</score>
</url>
</app>
下面是我的代码,如上所述,我正在读取完整的XML文件,然后从该XML文件获取哈希,名称,包等值。
public static void main(String[] args) {
try {
File fXmlFile = new File("C:\\ResourceFile\\app.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
System.out.println(doc);
} catch (Exception e) {
}
}
并且在我运行上述程序后。我总是得到下面的例外-
[Fatal Error] app.xml:2:22: Element type "app" must be followed by either attribute specifications, ">" or "/>".
知道为什么会发生吗?
您的xml中存在语法错误。元素的属性不应以逗号分隔。它应该像,
[如果您不想将其解析为XML
,而只显示为字符串,则可能要使用BufferedReader
和readLine()将其存储在StringBuilder
中,然后显示它。 How to read a file
try{
InputStream is = getAssets().open("HeadWork_JackWell.xml");
DocumentBuilderFactory dFactory= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dFactory.newDocumentBuilder();
Document doc= dBuilder.parse(is);
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
String s=sw.toString();
System.out.println(s);
} catch (Exception ex) {
throw new RuntimeException("Error converting to String", ex);
}