Java XML String to Document xml2Document(String xml)

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

Description

xml Document

License

Apache License

Declaration

public static Document xml2Document(String xml) 

Method Source Code


//package com.java2s;
/*/*from ww w.  j  a v a2  s  .  c  om*/
 * Copyright 2016-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.ByteArrayInputStream;
import java.io.IOException;

import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Main {
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final ThreadLocal<DocumentBuilderFactory> DOCUMENT_BUILDER_FACTORY = new ThreadLocal<DocumentBuilderFactory>() {
        @Override
        protected DocumentBuilderFactory initialValue() {
            return DocumentBuilderFactory.newInstance();
        }
    };

    public static Document xml2Document(String xml) {
        try {
            DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.get().newDocumentBuilder();
            return builder.parse(new ByteArrayInputStream(xml.getBytes(DEFAULT_CHARSET)));
        } catch (ParserConfigurationException ex) {
            throw new RuntimeException(ex);
        } catch (SAXException ex) {
            throw new RuntimeException(ex);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

Related

  1. toDocument(String xml)
  2. toDocument(String xml)
  3. toXmlDocument(final InputStream inputStream, final String path)
  4. toXMLDocument(String xmlString)
  5. writeDocumentToString(Document document)
  6. xmlNewDocument(final String tagName)
  7. xmlStringToDocument(String xml)
  8. xmlStringToDocument(String xmlInputString)