Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2003-2007 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.
  */
 
 package groovy.xml;
 
 
 import java.io.Reader;
 import java.util.Map;

A helper class for creating a W3C DOM tree

Author(s):
James Strachan
Version:
$Revision: 14130 $
 
 public class DOMBuilder extends BuilderSupport {
 
     Document document;
 
     public static DOMBuilder newInstance() throws ParserConfigurationException {
         return newInstance(falsetrue);
     }
 
     public static DOMBuilder newInstance(boolean validatingboolean namespaceAwarethrows ParserConfigurationException {
         DocumentBuilderFactory factory = FactorySupport.createDocumentBuilderFactory();
         factory.setNamespaceAware(namespaceAware);
         factory.setValidating(validating);
         return new DOMBuilder(factory.newDocumentBuilder());
     }

    
Creates a DocumentBuilder and uses it to parse the XML text read from the given reader. A non-validating, namespace aware parser is used.

Parameters:
reader the reader to read the XML text from
Returns:
the root node of the parsed tree of Nodes
Throws:
org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
java.io.IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
javax.xml.parsers.ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
See also:
parse(java.io.Reader,boolean,boolean)
 
     public static Document parse(Reader readerthrows SAXExceptionIOExceptionParserConfigurationException {
         return parse(readerfalsetrue);
     }

    
Creates a DocumentBuilder and uses it to parse the XML text read from the given reader, allowing parser validation and namespace awareness to be controlled.

Parameters:
reader the reader to read the XML text from
validating whether to validate the XML
namespaceAware whether the parser should be namespace aware
Returns:
the root node of the parsed tree of Nodes
Throws:
org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
java.io.IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
javax.xml.parsers.ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 
     public static Document parse(Reader readerboolean validatingboolean namespaceAware)
             throws SAXExceptionIOExceptionParserConfigurationException {
         DocumentBuilderFactory factory = FactorySupport.createDocumentBuilderFactory();
         factory.setNamespaceAware(namespaceAware);
         factory.setValidating(validating);
         DocumentBuilder documentBuilder = factory.newDocumentBuilder();
         return documentBuilder.parse(new InputSource(reader));
     }

    
A helper method to parse the given text as XML.

Parameters:
text the XML text to parse
Returns:
the root node of the parsed tree of Nodes
Throws:
org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
java.io.IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
javax.xml.parsers.ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
See also:
parse(java.io.Reader)
        return parse(new StringReader(text));
    }
    public DOMBuilder(Document document) {
        this. = document;
    }
    public DOMBuilder(DocumentBuilder documentBuilder) {
        this. = documentBuilder;
    }
    protected void setParent(Object parentObject child) {
        Node current = (Nodeparent;
        Node node = (Nodechild;
        current.appendChild(node);
    }
    protected Object createNode(Object name) {
        if ( == null) {
             = createDocument();
        }
        if (name instanceof QName) {
            QName qname = (QNamename;
            return .createElementNS(qname.getNamespaceURI(), qname.getQualifiedName());
        } else {
            return .createElement(name.toString());
        }
    }
    protected Document createDocument() {
        if ( == null) {
            throw new IllegalArgumentException("No Document or DOMImplementation available so cannot create Document");
        } else {
            return .newDocument();
        }
    }
    protected Object createNode(Object nameObject value) {
        Element element = (ElementcreateNode(name);
        element.appendChild(.createTextNode(value.toString()));
        return element;
    }
    protected Object createNode(Object nameMap attributesObject value) {
        Element element = (ElementcreateNode(nameattributes);
        element.appendChild(.createTextNode(value.toString()));
        return element;
    }
    protected Object createNode(Object nameMap attributes) {
        Element element = (ElementcreateNode(name);
        for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entryiter.next();
            String attrName = entry.getKey().toString();
            Object value = entry.getValue();
            if ("xmlns".equals(attrName)) {
                if (value instanceof Map) {
                    appendNamespaceAttributes(element, (Mapvalue);
                } else if (value instanceof String) {
                    setStringNS(element""value);
                } else {
                    throw new IllegalArgumentException("The value of the xmlns attribute must be a Map of QNames to String URIs");
                }
            } else if (attrName.startsWith("xmlns:") && value instanceof String) {
                setStringNS(elementattrName.substring(6), value);
            } else {
                String valueText = (value != null) ? value.toString() : "";
                element.setAttribute(attrNamevalueText);
            }
        }
        return element;
    }
    protected void appendNamespaceAttributes(Element elementMap<ObjectObjectattributes) {
        for (Map.Entry entry : attributes.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();
            if (value == null) {
                throw new IllegalArgumentException("The value of key: " + key + " cannot be null");
            }
            if (key instanceof String) {
                setStringNS(elementkeyvalue);
            } else if (key instanceof QName) {
                QName qname = (QNamekey;
                element.setAttributeNS(qname.getNamespaceURI(), qname.getQualifiedName(), value.toString());
            } else {
                throw new IllegalArgumentException("The key: " + key + " should be an instanceof of " + QName.class);
            }
        }
    }
    private void setStringNS(Element elementObject keyObject value) {
        String prefix = (Stringkey;
        element.setAttributeNS("http://www.w3.org/2000/xmlns/""".equals(prefix) ? "xmlns" : "xmlns:" + prefixvalue.toString());
    }
New to GrepCode? Check out our FAQ X