5

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.

4
  • 3
    If it doesn't have a root node, it's not really an XML file. Is adding a "dummy" root node not an option for some reason, or are you just interested in alternatives?
    – Anon.
    Commented Jul 7, 2010 at 2:43
  • 1
    Anon, thank you for your response, I am looking for something more elegant I guess. I know it's ironical, that I am looking for an elegant solution to a buggy problem. Nevertheless, just wondering, if there are other alternatives.
    – Seagull
    Commented Jul 7, 2010 at 6:42
  • I really do hope, that there is no such option. Why? Because 'relaxed' standard compliance like that doesn't help the enforcement of those standards at all. And, hopefully, there are more people, that don't want to deal with ad-hoc homegrown 'standards' like non-well-formed xml, than people, who do.
    – shylent
    Commented Jul 7, 2010 at 8:34
  • Even if you could correctly parse it, what would you expect as the output? A series of document nodes for the top-level elements? That's still pretty kludge-y. And it's really no different from just wrapping it and pulling them off yourself.
    – j flemm
    Commented Jul 7, 2010 at 20:20

6 Answers 6

5

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.

2
4

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.

1
  • 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.
    – Seagull
    Commented Jul 7, 2010 at 6:43
3

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">
]>
<dummy>
&data;
</dummy>
2
  • 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.
    – Seagull
    Commented Jul 7, 2010 at 6:46
  • 1
    You could have the outer wrapper in a string internal to your program; it doesn't actually need to exist on the filesystem. Commented Jul 8, 2010 at 8:42
1

You could use another parser like Jsoup. It can parse XML without a root.

0

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.

0

Here's what I did:

There's an old java.io.SequenceInputStream class, which is so old that it takes Enumeration rather than List or such.

With it, you can prepend and append the root element tags (<div> and </div> in my case) around your no-root XML stream. (You shouldn't do it by concatenating Strings due to performance and memory reasons.)

public void tryExtractHighestHeader(ParserContext context)
{
    String xhtmlString = context.getBody();
    if (xhtmlString == null || "".equals(xhtmlString))
        return;

    // The XHTML needs to be wrapped, because it has no root element.
    ByteArrayInputStream divStart = new ByteArrayInputStream("<div>".getBytes(StandardCharsets.UTF_8));
    ByteArrayInputStream divEnd = new ByteArrayInputStream("</div>".getBytes(StandardCharsets.UTF_8));
    ByteArrayInputStream is = new ByteArrayInputStream(xhtmlString.getBytes(StandardCharsets.UTF_8));
    Enumeration<InputStream> streams = new IteratorEnumeration(Arrays.asList(new InputStream[]{divStart, is, divEnd}).iterator());

    try (SequenceInputStream wrapped = new SequenceInputStream(streams);) {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDocument = builder.parse(wrapped);

From here you can do whatever you like, but keep in mind the extra element.

        XPath xPath = XPathFactory.newInstance().newXPath();
    }
    catch (Exception e) {
        throw new RuntimeException("Failed parsing XML: " + e.getMessage());
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.