0

I am using Castor XMLDiff to find the difference between 2 XML files. It compares two XML documents located at the given URL locations. Both my XML files are being generated at runtime and they are in the form of String. My question is how can I convert a String into an XML file, so that I can pass the file location as an argument.

I have a String in the following form:

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Header><MessageID>7dc1a6b9-5e84-4ee8-b801-816f4eccbe26</MessageID><MessageDate>.....

The method public XMLDiff(final String file1, final String file2) requires 2 file locations. Instead of a file location, I have the above stated string. What is the best way to persist this string in the form of an XML document, so that I can get its location and pass it to XMLDiff?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
One
  • 15
  • 2
  • 7
  • 5
    `how can I convert a String into an XML file` -- Erm... Open a text file and write the string out to it? – Robert Harvey Apr 29 '13 at 19:57
  • it's not clear how you want to convert. Could you post a "before and after" example of what you expect? – cahen Apr 29 '13 at 20:00
  • Take a look at http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java for some possible solutions. – Robert H Apr 29 '13 at 20:03
  • @cahen: I have edited my question and have included the xml string I want to persist. – One Apr 29 '13 at 20:08

2 Answers2

0

If the string contains XML data, then you just need to write it to disk. I would recommend a method such as FileUtils.write() from commons-io.

For example:

String xml = ...
FileUtils.write(new File("path/to/output"), xml, "UTF-8");

Of course, replace "UTF-8" with whatever encoding is advertised in your XML header.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
0

If you are using Java 7, you don't need 3rd party libs and still only need very short code via use of the new IO api:

Path path = Files.createTempFile("prefix", null);
Files.write(path, yourXMLString.getBytes(Charset.forName("UTF-8")) , StandardOpenOption.CREATE, StandardOpenOption.WRITE);
String pathToTheFile = path.toString();

With this you can simply create two temporary files, fill them with the XML string and then provide the path strings to your library function.

Marco
  • 1,430
  • 10
  • 18