Monday, 30 July 2012

Create xml Document from File or String & convert Document to String

  • Create xml Document from File or String
  • public Document buildDocumentFromExternalResource() throw Exception {
        String content = "....";
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        InputStream inputStream = new ByteArrayInputStream(content.getBytes());
        Document doc = docBuilder.parse(inputStream);
        // read from file
        doc = docBuilder.parse(new File("c:/temp/myContent.xml"));
    }
    
  • convert Document to String
  • public String convertDocumentToString(SOAPBody soapBody) throw Excepiton {
            Document doc = soapBody.getOwnerDocument();
            Source source = new DOMSource(doc);
            StringWriter out = new StringWriter();
            Result result = new StreamResult(out);
    
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(source, result);
    
            String content = out.toString();
       }
    

No comments:

Post a Comment