views:

93

answers:

4

I have this XML file which doesn't have a root node. Other than manually adding a "fake" root element, is there any way I would be able to parse an XML file in Java? Thanks.

+3  A: 

Your XML document needs a root xml element to be considered well formed. Without this you will not be able to parse it with an xml parser.

krock
Thank you krock, for your response. I am aware of the rules of XML well-formedness. However, I am dealing with a bad legacy scenario, and this is what I have to work with, so that's why fishing for options. Thanks.
Safder
+3  A: 

One way is to provide your own dummy wrapper without touching the original 'xml' (the not well formed 'xml') Need the word for that:

Syntax

<!DOCTYPE some_root_elem SYSTEM "/home/ego/some.dtd"
[
  <!ENTITY entity-name "Some value to be inserted at the entity">
]

Example:

<!DOCTYPE dummy [
<!ENTITY data SYSTEM "http://wherever-my-data-is"&gt;
]>
<dummy>
&data;
</dummy>
Brian
This is still wrapping something around the XML. What I am looking for is whether there is some way in Java to parse this XML by setting some property in some API.
Safder
You could have the outer wrapper in a string internal to your program; it doesn't actually need to exist on the filesystem.
Donal Fellows
A: 

I think even if any API would have an option for this, it will only return you the first node of the "XML" which will look like a root and discard the rest.

So the answer is probably to do it yourself. Scanner or StringTokenizer might do the trick.

Maybe some html parsers might help, they are usually less strict.

tulskiy
+3  A: 

I suppose you could create a new implementation of InputStream that wraps the one you'll be parsing from. This implementation would return the bytes of the opening root tag before the bytes from the wrapped stream and the bytes of the closing root tag afterwards. That would be fairly simple to do.

I may be faced with this problem too. Legacy code, eh?

Ian.

Edit: You could also look at java.io.SequenceInputStream which allows you to append streams to one another. You would need to put your prefix and suffix in byte arrays and wrap them in ByteArrayInputStreams but it's all fairly straightforward.

Ian Fairman
+1: This is what I have done in a similar situation, and it is indeed easy.
Don Roby