Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!!

like image 218
User_86 Avatar asked Mar 05 '13 08:03

User_86


People also ask

Which method converts the DOMDocument object into string?

DOMDocument implements the DOM API - access nodes via things like getElementById(), getElementsByClassName() , etc, and use saveXML() to write out a string.

Can we convert string to XML in Java?

To convert the String to XML document, we will use DocumentBuilderFactory and DocumentBuilder classes. "</BookStore>"; //Call method to convert XML string content to XML Document object.

What is XMLOutputter?

Outputs a JDOM document as a stream of bytes. The XMLOutputter can manage many styles of document formatting, from untouched to 'pretty' printed.


1 Answers

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

like image 88
AurA Avatar answered Sep 18 '22 22:09

AurA