Search code examples
c#java.netxmlxmldocument

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.


Solution

  • 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);