Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java equivalent for XmlDocument.LoadXml() from .NET?

In .NET C#, when trying to load a string into xml, you need to use XmlDocument type from System.Xml and do the following:

e.g:

string xmlStr = "<name>Oscar</name>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
Console.Write(doc.OuterXml);

This seems simple but how can I do this in Java? Is it possible to load a string into xml using something directly, short and simple like above and avoid implementing other methods for this?

Thanks in advance.

like image 989
Oscar Jara Avatar asked Jan 16 '23 06:01

Oscar Jara


1 Answers

Try this:

DocumentBuilderFactory documentBuildFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder doccumentBuilder = documentBuildFactory.newDocumentBuilder();
Document document = 
 doccumentBuilder.parse(new ByteArrayInputStream("<name>Oscar</name>".getBytes()));

You can traverse Oscar by:

String nodeText = document.getChildNodes().item(0).getTextContent() ;         
System.out.println(nodeText);

To transaform back:

TransformerFactory tFactory =  TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
//to print the string in sysout, System.out
StreamResult streamResult = new StreamResult(System.out);
transformer.transform(domSource, streamResult ); 

To get the result in String:

DOMSource source = new DOMSource(document);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult(outStream);
transformer.transform(source, result);
String resultString = new String( outStream.toByteArray());
System.out.println(resultString);
like image 150
Yogendra Singh Avatar answered Jan 29 '23 15:01

Yogendra Singh