Home
Categories
Dictionary
Download
Project Details
Changes Log
FAQ
License

Converting an XMLRoot to a Document


    1  Limitations
    2  Example
    3  Notes
    4  See also

The XMLDocumentBuilderFactory allows to convert an XMLRoot to a Document. It can be used for example with xsl transforms.

For example:
   XMLDocumentBuilderFactory factory = XMLDocumentFactory.getInstance();
   Document document = factory.parse(root);

Limitations

  • The resulting Document can not be updated
  • If the structure of the XML content is updated, you will need to create a new Document

Example

The following code creates an XMLRoot with the content of a File:
   URL xmlURL = XMLDocumentFactoryBaseTest.class.getResource("xmlPrint2.xml");
   XMLNodeUtilities2 utils = new XMLNodeUtilities2();
   XMLRoot root = utils.getRootNode(xmlURL);     
Now we can convert to a Document:
   XMLDocumentBuilderFactory factory = XMLDocumentBuilderFactory.getInstance();
   Document document = factory.parse(root);
The result can be used for an xsl transform[1]
For example here an empty transform which keeps the input XML file
:
   TransformerFactory factory = TransformerFactory.newInstance();
      
   URL xslURL = XMLDocumentFactoryBaseTest.class.getResource("empty.xsl");
   File xslFile = new File(xslURL.toURI().getPath());
   StreamSource streamSource = new StreamSource(xslFile);
   Transformer transformer = factory.newTransformer(streamSource);
   transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
   transformer.setOutputProperty(OutputKeys.METHOD, "xml");
   transformer.setOutputProperty(OutputKeys.INDENT, "yes");
   transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
   transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

   DOMSource xslDomSource = new DOMSource(document);
   outputFile = File.createTempFile("mdiutils", ".xml");
   try ( FileOutputStream outputStream = new FileOutputStream(outputFile)) {
      transformer.transform(xslDomSource, new StreamResult(outputStream));
   }

Notes

  1. ^ For example here an empty transform which keeps the input XML file

See also


Categories: packages | xml

Copyright 2006-2024 Herve Girod. All Rights Reserved. Documentation and source under the LGPL v2 and Apache 2.0 licences