cancel
Showing results for 
Search instead for 
Did you mean: 

how to transform a XML String to XML document

Former Member
0 Kudos

Hi,

how to transform a XML String to XML document

eg: String xmlstring="<root><main>Title</main></root>";

How can I transform this to XML Document??

Regards,

Mahesh

Accepted Solutions (0)

Answers (2)

Answers (2)

Former Member
0 Kudos

Hi Mahesh,

Clean your xml using followin code i.e remove all empty nodes. These empty nodes may have name as null or "#text".

try

{

Document doc = builder.parse(inputstrm);

Element root = doc.getDocumentElement();

NodeList ndLst = root.getChildNodes();

for(int i=0;i<ndLst.getLength();i++)

{

Node tmp = ndLst.item(i);

if(tmp.getNodeName().compareToIgnoreCase("") == 0 || tmp.getNodeName().compareToIgnoreCase("#text") == 0)

{

root.removeChild(tmp);

}

}

}

catch(Exception e)

{}

Hope this solves your problem

Regards,

Mayank

Former Member
0 Kudos

Refer this tutorial:

https://www.sdn.sap.com/irj/sdn/downloaditem?rid=/library/uuid/1208c2cd-0401-0010-4ab6-f4736074acc6

Don't go by the title of the document, in this tutorial, they explain how to convert an XML string to XML format and thus open it using an Excel application.

Regards,

Subramanian V.

Former Member
0 Kudos

Hi,

you have to use the DOM or SAX API.

DOM Example:


StringReader sr = new StringReader("<yourxml/>");
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory  = DocumentBuilderFactory.newInstance();
DocumentBuilder builder  = factory.newDocumentBuilder();
Document document = builder.parse(is);

Regards

Sebastian

Former Member
0 Kudos

Hi Sebastian,

Thanks for the support, I am using a DOM parser and was able to convert a string to an XML Document.

Now I have a problem that additional Newline characters get introduced in the document.

Eg : when I get the length of ChildNodes, I get the number of childnodes + the newlines in between each child node.

i.e if a node has 2 children I get the length as 5 (2children + 3 blank nodes).

Please let me know how to remove these newlines ??

Awaiting your kind responses.

Regards,

Mahesh