Java XML Document Parse parseXmlFragmentStr(Document doc, String fragment)

Here you can find the source of parseXmlFragmentStr(Document doc, String fragment)

Description

Parses a string containing XML and returns a DocumentFragment containing the nodes of the parsed XML.

License

Open Source License

Parameter

Parameter Description
doc a parameter
fragment a parameter

Declaration

public static DocumentFragment parseXmlFragmentStr(Document doc, String fragment) 

Method Source Code


//package com.java2s;

import java.io.IOException;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;

import org.w3c.dom.Node;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {
    private static DocumentBuilder domBuilder = null;

    /**/*from   w ww  .  j  a va2  s  .  com*/
     * Parses a string containing XML and returns a DocumentFragment containing the nodes of the parsed XML.
     * 
     * @param doc
     * @param fragment
     * @return
     */
    public static DocumentFragment parseXmlFragmentStr(Document doc, String fragment) {
        // Wrap the fragment in an arbitrary element
        fragment = "<fragment>" + fragment + "</fragment>";
        try {
            // Create a DOM builder and parse the fragment
            Document d = domBuilder.parse(new InputSource(new StringReader(fragment)));

            // Import the nodes of the new document into doc so that they
            // will be compatible with doc
            Node node = doc.importNode(d.getDocumentElement(), true);

            // Create the document fragment node to hold the new nodes
            DocumentFragment docfrag = doc.createDocumentFragment();

            // Move the nodes into the fragment
            while (node.hasChildNodes()) {
                docfrag.appendChild(node.removeChild(node.getFirstChild()));
            }

            // Return the fragment
            return docfrag;
        } catch (SAXException e) {
            // A parsing error occurred; the xml input is not valid
        } catch (IOException e) {
        }
        return null;
    }
}

Related

  1. parseXmlDocument(InputStream is, boolean namespaceAware)
  2. parseXMLDocument(String xml)
  3. parseXmlDocument(String xml, boolean namespaceAware)
  4. parseXMLDocument(String xmlDoc)
  5. parseXMLDocument(String xmlResponse)
  6. parseXMLString(Document document, String string)