Java Utililty Methods XML Document Parse

List of utility methods to do XML Document Parse

Description

The list of methods to do XML Document Parse are organized into topic(s).

Method

DocumentparseXMLDocument(String xml)
Parse an XML string into a document.
StringReader sr = new StringReader(xml);
DocumentBuilderFactory builderFactory;
DocumentBuilder builder;
try {
    builderFactory = DocumentBuilderFactory.newInstance();
    builder = builderFactory.newDocumentBuilder();
} catch (Exception e) {
    e.printStackTrace();
...
DocumentparseXmlDocument(String xml, boolean namespaceAware)
parse Xml Document
DocumentBuilder docBuilder = buildDocumentBuilder(namespaceAware);
Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));
doc.getDocumentElement().normalize();
return doc;
ElementparseXMLDocument(String xmlDoc)
Parse the given XML document, creating a DOM tree whose root Document object is returned.
Reader stringReader = new StringReader(xmlDoc);
InputSource inputSource = new InputSource(stringReader);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = null;
Document doc = null;
try {
    parser = dbf.newDocumentBuilder();
    doc = parser.parse(inputSource);
...
org.w3c.dom.DocumentparseXMLDocument(String xmlResponse)
Parses XML String
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlResponse));
return builder.parse(is);
DocumentFragmentparseXmlFragmentStr(Document doc, String fragment)
Parses a string containing XML and returns a DocumentFragment containing the nodes of the parsed XML.
fragment = "<fragment>" + fragment + "</fragment>";
try {
    Document d = domBuilder.parse(new InputSource(new StringReader(fragment)));
    Node node = doc.importNode(d.getDocumentElement(), true);
    DocumentFragment docfrag = doc.createDocumentFragment();
    while (node.hasChildNodes()) {
        docfrag.appendChild(node.removeChild(node.getFirstChild()));
    return docfrag;
} catch (SAXException e) {
} catch (IOException e) {
return null;
ElementparseXMLString(Document document, String string)
Parse a valid xml string and return the Element representing this string.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document subDoc = builder.parse(new InputSource(new StringReader(string)));
Element e = subDoc.getDocumentElement();
return (Element) document.importNode(e, true);