Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to read the full XML file as a String in Java

I am trying to read the whole XML file in Java. Below is my XML file-

<?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>

And below is my code, I am using to read the full XML file as shown above and then get hash, name, package etc value from that XML file.

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) {

}
}

And as soon as I am running the above program. I am always getting the below excpetion-

[Fatal Error] app.xml:2:22: Element type "app" must be followed by either attribute specifications, ">" or "/>".

Any idea why it is happening?

like image 366
AKIWEB Avatar asked Dec 01 '22 18:12

AKIWEB


2 Answers

If you don't want to parse it as XML and only to show as a String maybe you want to use a BufferedReader and readLine() store it in a StringBuilder and then show it. How to read a file

Example:

   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();
    }

EDIT In java 8 you can just simply use

String xml = Files.lines(Paths.getPath(path)).collect(Collectors.joining("\n"));
like image 59
nachokk Avatar answered Dec 14 '22 22:12

nachokk


There is syntax error in your xml. The attributes of the element should not be separated by a comma. It should be like,

<?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>
like image 35
Wenhao Ji Avatar answered Dec 14 '22 22:12

Wenhao Ji