Author

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

Читайте также:  Как вызвать случайное исключение python

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.

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.

Источник

Create source from string java

Representation of a source code unit and its contents that can be evaluated in an execution context . Each source is associated with the the ID of the language.

From a file on disk

Each file is represented as a canonical object, indexed by the absolute, canonical path name of the file. File content is read eagerly and may be optionally cached. Sample usage:

File file = new File(dir, name); assert name.endsWith(".java") : "Imagine proper file"; String language = Source.findLanguage(file); Source source = Source.newBuilder(language, file).build(); assert file.getName().equals(source.getName()); assert file.getPath().equals(source.getPath()); assert file.toURI().equals(source.getURI());

Read from an URL

URL resource = relativeClass.getResource("sample.js"); Source source = Source.newBuilder("js", resource) .build(); assert resource.toExternalForm().equals(source.getPath()); assert "sample.js".equals(source.getName()); assert resource.toURI().equals(source.getURI());

Each URL source is represented as a canonical object, indexed by the URL. Contents are read eagerly once the Source.Builder.build() method is called.

Source from a literal text

An anonymous immutable code snippet can be created from a string via the Source.newBuilder(String, java.lang.CharSequence, String) factory method:

Source source = Source.newBuilder("js", "function() + " return 'Hi';\n" + ">\n", "hi.js").buildLiteral(); assert "hi.js".equals(source.getName());

Reading from a stream

If one has a Reader one can convert its content into a Source via Source.newBuilder(String, java.io.Reader, String) method:

Reader stream = new InputStreamReader( relativeClass.getResourceAsStream("sample.js") ); Source source = Source.newBuilder("js", stream, "sample.js") .build(); assert "sample.js".equals(source.getName());

Reading from bytes

Sources can be created from bytes. Please note that all character related methods will throw an UnsupportedOperationException if that is the case.

byte[] bytes = new byte[] ; Source source = Source.newBuilder("llvm", ByteSequence.create(bytes), "").buildLiteral();

Attributes

The source object can be associated with various attributes like Source.getName() and Source.getURI() , Source.getMimeType() and these are immutable. The system makes the best effort to derive values of these attributes from the location and/or content of the Source object. However, to give the user that creates the source control over these attributes, the API offers an way to alter values of these attributes.

Character and byte based Sources

A source is byte or character based, or none of those when no content is specified. For literal sources it depends on whether the byte or character based factory method was used. When the source was loaded from a file or url then the default MIME type of the provided language will be used to determine whether bytes or characters should be loaded. The behavior can be customized by specifying a MIME type or content explicitly. If the specified or inferred MIME type starts with ‘text/ or the MIME types is null then it will be interpreted as character based, otherwise byte based.

Nested Class Summary

Method Summary

The number of text lines of a character based source, including empty lines; characters at the end of the source without a terminating newline count as a line.

Gets whether this source has been marked as internal, meaning that it has been provided by the infrastructure, language implementation, or system library.

Methods inherited from class java.lang.Object

Method Detail

getLanguage

getName

Returns the name of this resource holding a guest language program. An example would be the name of a guest language source code file. Name is supposed to be shorter than Source.getPath() .

getPath

The fully qualified name of the source. In case this source originates from a File , then the path is the normalized, canonical path for absolute files, or the relative path otherwise. If the source originates from an URL , then it’s the path component of the URL.

getURL

getURI

Get the URI of the source. Every source has an associated URI , which can be used as a persistent identification of the source. The URI returned by this method should be as unique as possible, yet it can happen that different sources return the same Source.getURI() — for example when content of a file on a disk changes and is re-loaded.

isInteractive

public boolean isInteractive()

Check whether this source has been marked as interactive. Interactive sources are provided by an entity which is able to interactively read output and provide an input during the source execution; that can be a user I/O through an interactive shell for instance. One can specify whether a source is interactive when building it .

isInternal

public boolean isInternal()

Gets whether this source has been marked as internal, meaning that it has been provided by the infrastructure, language implementation, or system library. Internal sources are presumed to be irrelevant to guest language programmers, as well as possibly confusing and revealing of language implementation details. On the other hand, tools should be free to make internal sources visible in (possibly privileged) modes that are useful for language implementors. One can specify whether a source is internal when building it .

getReader

getLength

Источник

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