cancel
Showing results for 
Search instead for 
Did you mean: 

convert string to xml

Former Member
0 Kudos

I have string xml_file =" <content is as below>"; <?xml version='1.0' encoding='UTF-8' standalone='no'?><Motor> <MotorElement><platno>jacket</platno> <type>blue</type> </MotorElement> <MotorElement><platno>skirt</platno> <type>red</type> </MotorElement> </Motor> how do i change to xxx.xml this is the sample to change a file to xml ...but i want a string to xml

Accepted Solutions (0)

Answers (2)

Answers (2)

Former Member
0 Kudos

Hi,

if i'm understanding correctly you need to convert your String into an InputStream.

You can use the following code:


//convert String to InputStream
ByteArrayInputStream str = new ByteArrayInputStream(xml_file.getBytes());

after that you can use the following method to create a org.w3c.dom.Document object:


	public static Document generateXMLDocument(InputStream content)
	{
		try
		{
			// Create a builder factory
			InputSource inputSourceContent = new InputSource(content);
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			factory.setValidating(false);
			Document doc = null;
			// Create the builder and parse the file
			//			Document doc = factory.newDocumentBuilder().parse(new File(filename));
			doc = factory.newDocumentBuilder().parse(content);

			return doc;
		}
		catch(DOMException domEx)
		{
			return null;
		}
		catch (SAXException e)
		{
			return null;
			// A parsing error occurred; the xml input is not valid
		}
		catch (ParserConfigurationException e)
		{
			return null;
		}
		catch (IOException e)
		{
			return null;
		}
		catch (Exception e)
		{
			return null;
		}

	}

Hope this help

Francesco

Former Member
0 Kudos

If I understand correctly, your requirement is to write the xml string , to a file. You have two ways to do this.

1. With your own logic to ensure the well-formedness and correctness of xml in place, open a FileOutputStream and write the contents of the string. no xml business here...its plain file i/o.

2. Load your xml text into DOM and you can then refer this link for the sample code to do the rest

http://www.exampledepot.com/egs/javax.xml.transform/WriteDom.html

Hope this helps..

-- Amol