试图以Java中的字符串形式读取完整的XML文件

问题描述 投票:3回答:3

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

知道为什么会发生吗?

java xml string file
3个回答
9
投票

您的xml中存在语法错误。元素的属性不应以逗号分隔。它应该像,


6
投票

[如果您不想将其解析为XML,而只显示为字符串,则可能要使用BufferedReader和readLine()将其存储在StringBuilder中,然后显示它。 How to read a file


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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.