Java XML Document from String loadXMLFromString(String xml)

Here you can find the source of loadXMLFromString(String xml)

Description

Build Document from String which contains XML content.

License

Open Source License

Parameter

Parameter Description
xml String which contains XML content.

Return

or null if convert has failed.

Declaration

public static Document loadXMLFromString(String xml) 

Method Source Code

//package com.java2s;
/**/*from  w  w  w.j a  va 2  s.  c o m*/
 * Copyright (c) 2015 openHAB UG (haftungsbeschraenkt) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {
    /**
     * Build {@link Document} from {@link String} which contains XML content.
     * 
     * @param xml
     *            {@link String} which contains XML content.
     * @return {@link Document} or null if convert has failed.
     */
    public static Document loadXMLFromString(String xml) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(xml));
            return builder.parse(is);

        } catch (ParserConfigurationException | SAXException | IOException e) {
            // Silently ignore exception and return null.
        }

        return null;
    }
}

Related

  1. loadDocument(String documentContent)
  2. loadDocument(String xmlString)
  3. loadXml(String xml)
  4. loadXMLFrom(String xml)
  5. loadXMLFromString(String xml)
  6. loadXMLFromString(String xml)
  7. readString(String xml)