Reputation: 19632
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?
Upvotes: 6
Views: 84369
Reputation: 14413
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"));
Upvotes: 11
Reputation: 11
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);
}
Upvotes: 0
Reputation: 5161
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>
Upvotes: 9