How to convert String having contents in XML format into JDom document
Asked Answered
P

2

12

How convert String having contents in XML format into JDom document.

i am trying with below code:

String docString = txtEditor.getDocumentProvider().getDocument(
txtEditor.getEditorInput()).get();

SAXBuilder sb= new SAXBuilder();

doc = sb.build(new StringReader(docString));

Can any one help me to resolve above problem. Thanks in advance!!

Patel answered 5/3, 2013 at 8:54 Comment(0)
A
18

This is how you generally parse an xml to Document

try {
  SAXBuilder builder = new SAXBuilder();
  Document anotherDocument = builder.build(new File("/some/directory/sample.xml"));
} catch(JDOMException e) {
  e.printStackTrace();
} catch(NullPointerException e) {
  e.printStackTrace();
}

This is taken from JDOM IBM Reference

In case you have string you can convert it to InputStream and then pass it

String exampleXML = "<your-xml-string>";
InputStream stream = new ByteArrayInputStream(exampleXML.getBytes("UTF-8"));
Document anotherDocument = builder.build(stream);

For the various arguments builder.build() supports you can go through the api docs

Acord answered 5/3, 2013 at 8:59 Comment(4)
Thanks for your quick response. Code pasted by you works fine to create a new document using the file available at particular path. But in my case, i need to create/convert a string which has content in XML format into Document.Patel
Yes, code works fine to create a new document from an existing .xml file. But here i don't have any xml file. i getting this string (which has contents in xml format) from some where else. As you can see it my code: String docString = txtEditor.getDocumentProvider().getDocument( txtEditor.getEditorInput()).get();Patel
sry.. solved the typo issue.. exampleXML is the String in xml formatAcord
Actually, it seems that code pasted by me also working fine. there was problem in somewhere else in my code. But thanks for looking into this. And you provided different way to do the same.Hope this approach will help to any one.Patel
C
10

This is a FAQ that shold have an answer more accessible than the actual FAQ: How do I build a document from a String?

So, I have created issue #111

For what it's worth, I have previously improved the error messages for this situation (see the previous issue #63 and now you should have an error that says:

MalformedURLException mx = new MalformedURLException(
    "SAXBuilder.build(String) expects the String to be " +
    "a systemID, but in this instance it appears to be " +
    "actual XML data.");

Bottom line is that you should be using:

Document parseddoc = new SaxBuilder().build(new StringReader(myxmlstring));

rolfl

Countess answered 5/3, 2013 at 11:37 Comment(1)
Actually, it seems that code pasted by me also working fine. there was problem in somewhere else in my code. But thanks for looking into this.Patel

© 2022 - 2024 — McMap. All rights reserved.