cancel
Showing results for 
Search instead for 
Did you mean: 

How To Convert XML into String?

Former Member
0 Kudos

Hi,

I have a requirement in which I need to convert the data from XML file to string.

E.g.

<Drawing>

<DrawingSpecification>

<Header>

<SoldTo>SDN</SoldTo>

<SoldToName>SAP</SoldToName>

<Date/>

<Manager>CEO</Manager>

< Plant>INDIA</Name>

<Items>

<Item>

< MaterialNumber>MatNum12</ MaterialNumber>

<ProductNumber>ProName12</ ProductNumber>

</Item>

</Items>

< ClientId>ClientID123</ ClientId>

<FileName>FileName123</FileName>

<Type/>

< TemplateName/>

</DrawingSpecification>

<Image contentType=""/>

< /Drawing>

Output should be like:

< File>

< Content> SDN SAP CEO INDIA MatNum12 ProName12 ClientID123 FileName123</Content>

< /File>

Please provide solution for the same.

Thanks,

Abhishek.

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Kudos

Hi,

You can use DOM Parser for this. Check these links.

http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM3.html

http://www.developerfusion.com/code/2064/a-simple-way-to-read-an-xml-file-in-java/

Once the string is obtained, you can create the output file.

Regards,

Harini S

Answers (1)

Answers (1)

Former Member
0 Kudos

what about something like this


package test;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Test {

	public static void main(String args[]) throws Exception {

		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(new File("test.xml"));

		StringBuffer buffer = new StringBuffer();

		appendChildren(buffer, doc.getChildNodes());

		System.out.println(buffer.toString());
	}

	private static void appendChildren(StringBuffer buffer, NodeList list) {
		for (int i = 0; i < list.getLength(); i++) {
			Node node = list.item(i);
			if (node.getNodeValue() != null) {
				if (node.getNodeValue().trim().length() > 0) {
					buffer.append(node.getNodeValue()).append("|");
				}
			}
			appendChildren(buffer, node.getChildNodes());
		}
	}

}

...btw: IMHO the use of this forum is to get an answer to an particular question - not to ask for complete solutions - create the solution yourself an ask if you are stuck somewhere (with a bit of research (google) it is not hard to find a solution for your problem)

regards franz

...close thread if question is answered