Pedantic
Pedantic

Reputation: 1378

Convert a String to w3c.dom.Element: XMLParseException:Start of root element expected

I found the following piece of code from a blog, when running it I get an exception

XMLParseException:Start of root element expected. at 9th line.

Can any one explain why I get the Exception and suggest any other way for converting String to an element?

String s = "Hello DOM Parser";
java.io.InputStream sbis = new java.io.StringBufferInputStream(s);
javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory.newInstance();
b.setNamespaceAware(false);
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilder db = null;
db = b.newDocumentBuilder();
doc = db.parse(sbis);     

org.w3c.dom.Element e = doc.getDocumentElement();

Upvotes: 1

Views: 13866

Answers (3)

Thizzer
Thizzer

Reputation: 16663

Like said in the comment, "Hello DOM Parser" is not a XML element. And so the parser doesn't know what to do with it. I don't know what kind document you are building, but if you want HTML you can embed the text in a html tag for example;

<div>Hello DOM Parser</div>
<span>Hello DOM Parser</span>

if you are building XML, you can embed the text in any random html tag;

<mytag>Hello DOM Parser</mytag>

Some explanation on DOM; http://www.w3.org/DOM

To answer your question, to convert a String to a w3c Element, you can use createElement;

Element hello = document.createElement("hello");          
hello.appendChild(document.createTextNode("Hello DOM Parser"));

This results in;

<hello>Hello DOM Parser</hello>

Upvotes: 1

kostja
kostja

Reputation: 61558

To create a DOM Element with a custom tag (which I assume is what you want, but can't be sure), you can use the following approach:

String customTag = "HelloDOMParser";

Document doc = documentBuilder.newDocument();       

String fullName = nameSpacePrefix + ":" + customTag;

Element customElement = document.createElementNS(namespaceUri, fullName);

doc.appendChild(customElement);

I am assuming you know the namespace URI and your prefix (if any). If you don't use namespaces, just use the createElement() method instead.

Upvotes: 1

James Jithin
James Jithin

Reputation: 10555

The parse method of DocumentBuilder accept the input stream which contains the xml content. The following change will work for you:

String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root><elem1>Java</elem1></root>";

Try to avoid using the deprecated classes such as StringBufferInputStream. You can refer to the document below to know more about Java XML parsing.

http://www.java-samples.com/showtutorial.php?tutorialid=152

Upvotes: 0

Related Questions