4

我正在尝试用 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 "/>".

知道为什么会这样吗?

4

3 回答 3

9

您的 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>
于 2013-07-10T02:20:32.387 回答
9

如果您不想将其解析为XML并且仅显示为字符串,则可能您想使用 aBufferedReader和 readLine() 将其存储在 a 中StringBuilder然后显示它。如何读取文件

例子:

   public String readFile(String path) throws IOException{
            StringBuilder sb = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new FileReader(path))){

        while ((String sCurrentLine = br.readLine()) != null) {
            sb.append(sCurrentLine);
        }

    }

          return sb.toString();
    }

编辑在java 8中你可以简单地使用

String xml = Files.lines(Paths.getPath(path)).collect(Collectors.joining("\n"));
于 2013-07-10T02:24:04.617 回答
0
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);
    }
于 2015-05-18T11:42:14.630 回答