I am trying to copy an entire XML document, tagnames/tagtypes irrelavant, into a String varible. Language to be used is Java. I used ReadAllText to do it in C#, but I need to find an equivalent of that command in Java or another idea to be able to have the entire XML document as a String. I have been working on this for a while now. This is part of a bigger project. This is the only thing that is left to be done. Any suggestions? Thanks in Advance.
-
4http://stackoverflow.com/questions/5511096/java-convert-formatted-xml-file-to-one-line-string – Shawn Aug 16 '11 at 18:52
-
@Shawn: +1, perfect duplicate. – Bhesh Gurung Aug 16 '11 at 19:01
-
Don't forget to give feedback on an answer and select a best answer – hbhakhra Aug 16 '11 at 19:01
5 Answers
Well since this is java and not a scripting language, you will just need to use a scanner or file reader and read it line by line and append it into a single string.
This website has a great overview of file io in java. I actually learned a lot even after knowing about file io.
Here is a sample of what you could do:
private void processFile(File file)
{
StringBuilder allText = new StringBuilder();
String line;
Scanner reader = null;
try {
FileInputStream fis = new FileInputStream(propertyFile);
InputStreamReader in = new InputStreamReader(fis, "ISO-8859-1");
reader = new Scanner(in);
while(reader.hasNextLine() && !errorState)
{
line = reader.nextLine();
allText.append(line);
}
} catch (FileNotFoundException e)
{
System.err.println("Unable to read file");
errorState=true;
} catch (UnsupportedEncodingException e) {
System.err.println("Encoding not supported");
errorState=true;
}
finally
{
reader.close();
}
}

- 4,206
- 2
- 22
- 36
-
-
If you liked the answer then you should select it as the best answer...I know you are new, so I am just trying to tell you some Stack Overflow etiquette. – hbhakhra Aug 16 '11 at 21:16
Try following code:
public String convertXMLFileToString(String fileName)
{
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
InputStream inputStream = new FileInputStream(new File(fileName));
org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
StringWriter stw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(doc), new StreamResult(stw));
return stw.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

- 3,639
- 1
- 18
- 23
-
Thank You so much. I figured it out though! I appreciate the help. This is a different way of doing it though. Always nice to learn something new! – Balaji Aug 16 '11 at 20:48
use an StringWriter
with a StreamResult
.
note, be very careful what you do with that string after that. if you later write it to a stream/byte[] of some sort using the wrong character encoding, you will generate broken xml data.

- 52,909
- 5
- 76
- 118
I used a buffered Reader the last time I did this. Worked well.
String output = "";
try {
FileInputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = br.readLine()) != null) {
output = output + line;
}
br.close();
is.close();
} catch(IOException ex) {
//LOG!
}
My original implementation was to use an actual buffer but I seemed to keep having issues with flushing the buffer so I went this way which is super easy.

- 593
- 5
- 19
-
Keep in mind that the BufferedReader will eat the \n at the end of each line. – RealHowTo Aug 17 '11 at 02:17
-
This was ultimately my goal. I was using XStream as a serializer which would choke on the new line characters. Ultimately I didn't want those characters in any version of my code as I try to ignore the plain-text readability of XML and use some XML friendly viewer. – PaulSCoder Aug 22 '11 at 14:35
-
Hey, do you know how to copy certaing specific tag contents into a string? THere is another question on my profile which has the details. I would really be thankful to you if you could help me out since you seem like a good coder! THanks! – Balaji Sep 11 '11 at 17:29
Many answers that get it almost, but not quite, correct.
- If you use a BufferedInputStream and read lines, the result is missing line breaks
- If you use a BufferedReader or a Scanner and read lines, the result is missing the original line breaks an the encoding may be wrong.
- If you use a Writer in a Result, the encoding may not match the source
If you positively know the source encoding, you can do this:
String file2string(File f, Charset cs) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
InputStream in = new BufferedInputStream(new FileInputStream(f));
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
return out.toString(cs.name());
}
If you don't know the source encoding, rely on the XML parser to detect it and control the output:
String transform2String(File f, Charset cs) throws IOException,
TransformerFactoryConfigurationError, TransformerException {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.ENCODING, cs.name());
ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
t.transform(new StreamSource(new BufferedInputStream(
new FileInputStream(f))), new StreamResult(out));
return out.toString(cs.name());
}

- 12,204
- 2
- 26
- 36