Author

Java to xml dom document

Defines the API to obtain DOM Document instances from an XML document. Using this class, an application programmer can obtain a Document from XML. An instance of this class can be obtained from the DocumentBuilderFactory.newDocumentBuilder() method. Once an instance of this class is obtained, XML can be parsed from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources. Note that this class reuses several classes from the SAX API. This does not require that the implementor of the underlying DOM implementation use a SAX parser to parse XML document into a Document . It merely requires that the implementation communicate with the application using these existing APIs.

Constructor Summary

Method Summary

Methods declared in class java.lang.Object

Constructor Detail

DocumentBuilder

protected DocumentBuilder()

Method Detail

reset

Reset this DocumentBuilder to its original configuration. DocumentBuilder is reset to the same state as when it was created with DocumentBuilderFactory.newDocumentBuilder() . reset() is designed to allow the reuse of existing DocumentBuilder s thus saving resources associated with the creation of new DocumentBuilder s. The reset DocumentBuilder is not guaranteed to have the same EntityResolver or ErrorHandler Object s, e.g. Object.equals(Object obj) . It is guaranteed to have a functionally equal EntityResolver and ErrorHandler .

parse

public Document parse​(InputStream is) throws SAXException, IOException

Parse the content of the given InputStream as an XML document and return a new DOM Document object. An IllegalArgumentException is thrown if the InputStream is null.

parse

public Document parse​(InputStream is, String systemId) throws SAXException, IOException

Parse the content of the given InputStream as an XML document and return a new DOM Document object. An IllegalArgumentException is thrown if the InputStream is null.

parse

public Document parse​(String uri) throws SAXException, IOException

Parse the content of the given URI as an XML document and return a new DOM Document object. An IllegalArgumentException is thrown if the URI is null null.

parse

public Document parse​(File f) throws SAXException, IOException

Parse the content of the given file as an XML document and return a new DOM Document object. An IllegalArgumentException is thrown if the File is null null.

parse

public abstract Document parse​(InputSource is) throws SAXException, IOException

Parse the content of the given input source as an XML document and return a new DOM Document object. An IllegalArgumentException is thrown if the InputSource is null null.

isNamespaceAware

public abstract boolean isNamespaceAware()

isValidating

public abstract boolean isValidating()

setEntityResolver

Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed. Setting this to null will result in the underlying implementation using it’s own default implementation and behavior.

Читайте также:  Dotted lines in css

setErrorHandler

Specify the ErrorHandler to be used by the parser. Setting this to null will result in the underlying implementation using it’s own default implementation and behavior.

newDocument

getDOMImplementation

getSchema

Get a reference to the the Schema being used by the XML processor. If no schema is being used, null is returned.

isXIncludeAware

public boolean isXIncludeAware()

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java Convert String to XML DOM Example

To convert XML string to XML Dom, we need the following classes:

  • javax.xml.parsers.DocumentBuilder : Defines the API to obtain XML DOM Document instances from XML content from various input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.
  • javax.xml.parsers.DocumentBuilderFactory : Defines a factory API that enables applications to obtain a parser ( DocumentBuilder ) that produces DOM object trees from XML content.
  • org.w3c.dom.Document : It represents the entire XML DOM. Conceptually, it is the root of the document tree, and provides the access to the document’s data further down into the tree, through factory methods.
  • java.io.StringReader : Create a stream from String content. DocumentBuilder uses this stream to read XML content for parsing.
import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class ConvertStringToXML < public static void main(String[] args) < final String xmlStr + " Lokesh Gupta" + " " + " " + " Brian Lara" + " " + " " + ""; //Use method to convert XML string content to XML Document object Document doc = convertStringToXMLDocument(xmlStr); //Verify XML document is build correctly System.out.println("Root Node : " + doc.getFirstChild().getNodeName()); NodeList nodeList = doc.getElementsByTagName("employee"); for (int itr = 0; itr < nodeList.getLength(); itr++) < Node node = nodeList.item(itr); System.out.println("\nNode Name : " + node.getNodeName()); if (node.getNodeType() == Node.ELEMENT_NODE) < Element eElement = (Element) node; System.out.println("Name: "+ eElement.getElementsByTagName("name").item(0).getTextContent()); System.out.println("Title: "+ eElement.getElementsByTagName("title").item(0).getTextContent()); >> > private static Document convertStringToXMLDocument(String xmlString) < //Parser that produces DOM object trees from XML content DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //API to obtain DOM Document instance DocumentBuilder builder = null; try < //Create DocumentBuilder with default configuration builder = factory.newDocumentBuilder(); //Parse the content to Document object Document doc = builder.parse(new InputSource(new StringReader(xmlString))); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > >
Root Node : employees Node Name : employee Name: Lokesh Gupta Title: Author Node Name : employee Name: Brian Lara Title: Cricketer

2. Convert XML File to XML Document

To get the XML dom from XML file, instead of passing the XML string to DocumentBuilder, pass the file path to let the parser read the file content directly.

Читайте также:  Image Padding

We have employees.xml file which has XML content, we will read to get XML document.

  Lokesh Gupta   Brian Lara   
import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class StringtoXMLExample < public static void main(String[] args) < final String xmlFilePath = "employees.xml"; //Use method to convert XML string content to XML Document object Document doc = convertXMLFileToXMLDocument( xmlFilePath ); //Verify XML document is build correctly System.out.println(doc.getFirstChild().getNodeName()); >private static Document convertXMLFileToXMLDocument(String filePath) < //Parser that produces DOM object trees from XML content DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //API to obtain DOM Document instance DocumentBuilder builder = null; try < //Create DocumentBuilder with default configuration builder = factory.newDocumentBuilder(); //Parse the content to Document object Document doc = builder.parse(new File(filePath)); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > >

Drop me your questions in the comments section.

Источник

Writing Out a DOM as an XML File

After you have constructed a DOM (either by parsing an XML file or building it programmatically) you frequently want to save it as XML. This section shows you how to do that using the Xalan transform package.

Using that package, you will create a transformer object to wire a DOMSource to a StreamResult. You will then invoke the transformer’s transform() method to write out the DOM as XML data.

Reading the XML

The first step is to create a DOM in memory by parsing an XML file. By now, you should be getting comfortable with the process.

The code discussed in this section is in the file TransformationApp01.java. Download the XSLT examples and unzip them into the install-dir/jaxp-1_4_2-release-date/samples directory.

The following code provides a basic template to start from. It is basically the same code as was used at the start of the Document Object Model lesson.

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.w3c.dom.Document; import org.w3c.dom.DOMException; import java.io.*; public class TransformationApp01 < static Document document; public static void main(String argv[]) < if (argv.length != 1) < System.err.println("Usage: java TransformationApp01 filename"); System.exit (1); >DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try < File f = new File(argv[0]); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(f); >catch (SAXParseException spe) < // Error generated by the parser System.out.println("\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId()); System.out.println(" " + spe.getMessage() ); // Use the contained exception, if any Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace(); >catch (SAXException sxe) < // Error generated by this application // (or a parser-initialization error) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); >catch (ParserConfigurationException pce) < // Parser with specified options // cannot be built pce.printStackTrace(); >catch (IOException ioe) < // I/O error ioe.printStackTrace(); >> >

Creating a Transformer

The next step is to create a transformer you can use to transmit the XML to System.out. To begin with, the following import statements are required.

import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*;

Here, you add a series of classes that should now be forming a standard pattern: an entity (Transformer), the factory to create it (TransformerFactory), and the exceptions that can be generated by each. Because a transformation always has a source and a result, you then import the classes necessary to use a DOM as a source (DOMSource) and an output stream for the result (StreamResult).

Читайте также:  Controller in java servlet

Next, add the code to carry out the transformation:

Here, you create a transformer object, use the DOM to construct a source object, and use System.out to construct a result object. You then tell the transformer to operate on the source object and output to the result object.

In this case, the «transformer» is not actually changing anything. In XSLT terminology, you are using the identity transform, which means that the «transformation» generates a copy of the source, unchanged.

You can specify a variety of output properties for transformer objects, as defined in the W3C specification at http://www.w3.org/TR/xslt#output. For example, to get indented output, you can invoke the following method:

% transformer.setOutputProperty(OutputKeys.INDENT, "yes");

Finally, the following highlighted code catches the new errors that can be generated:

> catch (TransformerConfigurationException tce) System.out.println("* Transformer Factory error"); System.out.println(" " + tce.getMessage()); Throwable x = tce; if (tce.getException() != null) x = tce.getException(); x.printStackTrace(); > catch (TransformerException te) System.out.println("* Transformation error"); System.out.println(" " + te.getMessage()); Throwable x = te; if (te.getException() != null) x = te.getException(); x.printStackTrace(); > catch (SAXParseException spe) < // . >
  • TransformerExceptions are thrown by the transformer object.
  • TransformerConfigurationExceptions are thrown by the factory.
  • To preserve the XML document’s DOCTYPE setting, it is also necessary to add the following code:

import javax.xml.transform.OutputKeys; . if (document.getDoctype() != null)

To find out more about configuring the factory and handling validation errors, see Reading XML Data into a DOM.

Running the TransformationApp01 Sample

% cd install-dir/jaxp-1_4_2-release-date/samples.
% javac TransformationApp01.java
% java TransformationApp01 data/foo.xml

Writing Out a Subtree of the DOM

It is also possible to operate on a subtree of a DOM. In this section, you will experiment with that option.

The code discussed in this section is in TranformationApp02.java. If you have not done so already, download the XSLT examples and unzip them into the install-dir/jaxp-1_4_2-release-date/samples directory.

The only difference in the process is that now you will create a DOMSource using a node in the DOM, rather than the entire DOM. The first step is to import the classes you need to get the node you want, as shown in the following highlighted code:

import org.w3c.dom.Document; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.NodeList; 

The next step is to find a good node for the experiment. The following highlighted code selects the first element.

In Creating a Transformer, the source object was constructed from the entire document by the following line of code

DOMSource source = new DOMSource(document);

However, the highlighted line of code below constructs a source object that consists of the subtree rooted at a particular node.

DOMSource source = new DOMSource(node); StreamResult result = new StreamResult(System.out); transformer.transform(source, result);

Running the TranformationApp02 Sample

% cd install-dir/jaxp-1_4_2-release-date/samples.
% javac xslt/TranformationApp02.java
% java TranformationApp02 data/foo.xml

Источник

Оцените статью