Java: Split XML with multiple roots.

I need to split an xml file which has multiple roots into files having one root. How can I achieve this?
Who is Participating?
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Ok, so your options are fairly limited then. The problem being that the file is not a valid XML file, so no parsers are ever going to touch it. You can either :-

  • Treat it like a simple text file, reading it in and just start a new file everytime you encounter the line with </GamerProfile>   (and hope that that tag never appears nested deeper in the document, i.e. it can cause other issues)
  • Modify the file, either manually or on the fly in the code, to add a top level element that covers all the GamerProfile elements, and then you would be able to write a parser that reads the (now) well-formed XML and write out individual GamerProfile elements to separate files

Unfortunately, I don't know enough C++ these days to help you further (only Java) but this should at least get you thinking in the right direction.
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Can you provide example of the file that you wish to process? Also, you mention Java in the title, is this what you are looking to implement a solution with? Can you provide some more info on the context of what you are trying to do? i.e. a web app, a console app, one off, etc? Also, is this part of a larger solution of just something standalone?
VakilsDeveloperAuthor Commented:
I do not have to use Java to split file, it can be any tool accessible in Windows, I do have C++. The xml parser is in java(web app), but it will not load because of multiple roots. So I have to split into multiple files based on each root. Then the parser can pick up the file and process. I cannot change parsing code, or the xml structure. I cannot ask vendor to give me multiple files, so I am stuck with splitting the file. Attached is an example with multiple roots. The  loader of portion of java web application picks up the file.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.