Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
PETALS - PETALS Services Platform. Copyright (c) 2006 EBM Websourcing This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ------------------------------------------------------------------------- $Id: XMLUtil.java 98 2006-02-24 16:18:48Z alouis $ -------------------------------------------------------------------------
 
 
 package org.ow2.petals.component.framework.util;
 
 import java.util.List;
 
 
Contains utilities methods for XML operations.

Author(s):
alouis - EBMWebsourcing
ddesjardins - EBMWebsourcing
gblondelle - EBMWebsourcing
Since:
1.0
 
 public final class XMLUtil {
 
     private static final String XML_ENCODING_ATTRIBUTE = "encoding";
 
     private static final String XML_HEADER_END = "?>";
 
     private static final String XML_HEADER_START = "<?xml";
 
     private static final String DEFAULT_CHARSET_ENCODING = "UTF-8";
 
     private static final Logger LOGGER = Logger.getLogger(XMLUtil.class.getName());
 
     private XMLUtil() {
         // Do nothing
     }

    
Create an attribute node with the specified value

Parameters:
document XML document
att attribute name
value attribute value
Returns:
an attribute, null if the document is null
 
     public static Node createAttribute(final Document documentfinal String attfinal String value) {
         Node element = null;
         if (document != null) {
             element = document.createAttribute(att);
             element.setNodeValue(value);
         }
         return element;
     }

    
Create a node with the specified name, attributes and values. attVal is a suite : att1,val1,att2,val2,...

Parameters:
document xlm document
nodeName node name
attVal attribute values
Returns:
the node with its attribute, null if the array is not correct or the document is null.
    public static Node createNode(final Document documentfinal String nodeName,
            final String... attVal) {
        Node element = null;
        if (document != null && attVal.length % 2 == 0) {
            element = document.createElement(nodeName);
            for (int i = 0; i < attVal.lengthi = i + 2) {
                element.getAttributes().setNamedItem(
                        createAttribute(documentattVal[i], attVal[i + 1]));
            }
        }
        return element;
    }

    
Search for a child with the given nodeName. If recursive, search in all the child of first level, then if not found, search in the 2nd level of the first child, ...

Deprecated:
Use findChild(org.w3c.dom.Node,java.lang.String,java.lang.String,boolean) with a namespace set to null.
Parameters:
node parent node
nodeName node name
recursive boolean to know if we got through the xml tree
Returns:
a node
    @Deprecated
    public static Node findChild(final Node nodefinal String nodeNamefinal boolean recursive) {
        node.normalize();
        Node result = null;
        NodeList nl = node.getChildNodes();
        if (node != null && nodeName != null) {
            result = lookupNodeInNodeList(nodeNamenl);
            // now, search recursively if required
            if (result == null && recursive) {
                for (int i = 0; i < nl.getLength() && result == nulli++) {
                    result = findChild(nl.item(i), nodeNametrue);
                }
            }
        }
        return result;
    }

    
lookup a node in a node list.

Deprecated:
Use lookupNodeInNodeList(java.lang.String,java.lang.String,org.w3c.dom.NodeList) with a namespace set to null.
Parameters:
nodeName the local name of the name
nl the list of node
Returns:
the node naming by the nodeName
    @Deprecated
    private static Node lookupNodeInNodeList(final String nodeNamefinal NodeList nl) {
        Node result = null;
        for (int i = 0; i < nl.getLength() && result == nulli++) {
            if (nodeName.equals(nl.item(i).getNodeName())) {
                result = nl.item(i);
            }
        }
        return result;
    }

    
lookup a node in a node list.

Parameters:
nodeName the local name of the name
nameSpace the namespace of this node. If null, the namespace is ignored
nl the list of node
Returns:
the node naming by the nodeName
    private static Node lookupNodeInNodeList(final String nodeNamefinal String namespace,
            final NodeList nl) {
        Node result = null;
        for (int i = 0; i < nl.getLength() && result == nulli++) {
            if (((namespace != null) && (nl.item(i).getNamespaceURI() != null))
                    && ((nl.item(i).getNamespaceURI().equals(namespace)) && (nodeName.equals(nl
                            .item(i).getLocalName())))) {
                result = nl.item(i);
            } else if (nodeName.equals(nl.item(i).getLocalName())) {
                result = nl.item(i);
            }
        }
        return result;
    }

    
Search for a child with the given nodeName. If recursive, search in all the child of firdt level, then if not found, search in the 2nd level of the first child, ...

Parameters:
node parent node
namespaceURI The namespaceURI of the node. if null, the namespace is ignored
nodeName node name
recursive boolean to know if we got through the xml tree
Returns:
a node
    public static Node findChild(final Node nodefinal String nodeNamefinal String namespaceURI,
            final boolean recursive) {
        node.normalize();
        Node result = null;
        NodeList nl = node.getChildNodes();
        if (node != null && nodeName != null) {
            result = lookupNodeInNodeList(nodeNamenamespaceURInl);
            // now, search recursively if required
            if (result == null && recursive) {
                for (int i = 0; i < nl.getLength() && result == nulli++) {
                    result = findChild(nl.item(i), nodeNamenamespaceURItrue);
                }
            }
        }
        return result;
    }

    
Transform an XML org.w3c.dom.Node into a String

Parameters:
node the XML org.w3c.dom.Node to parse
Returns:
the resulting String, null if node is null
Throws:
javax.xml.transform.TransformerException if errors occured during transformation
    public static String parseToString(final Node nodethrows TransformerException {
        String result = null;
        if (node != null) {
            node.normalize();
            final StringWriter stringWriter = new StringWriter();
            final Transformer transformer = Transformers.getXmlWithoutDeclarationTransformer();
            try {
                transformer.transform(new DOMSource(node), new StreamResult(stringWriter));
            } finally {
                transformer.reset();
            }
            final StringBuffer buffer = stringWriter.getBuffer();
            result = buffer.toString();
        }
        return result;
    }

    
Return the value of the attribute in the node

Parameters:
n the node
attName the name of the attribute
Returns:
the value of the attribute (can be empty), null if not found
    public static String getAttributeValue(final Node nfinal String attName) {
        String ret = null;
        if (n != null) {
            NamedNodeMap atts = n.getAttributes();
            Node att = atts.getNamedItem(attName);
            if (att != null) {
                ret = att.getNodeValue();
            }
        }
        return ret;
    }

    
Return the value of the attribute in the node. Throws an exception if missing attribute.

Parameters:
n the node
attName the name of the attribute, must be non null
Returns:
the value of the attribute (can be empty).
Throws:
java.lang.NullPointerException if attribute not found in the node
    public static String getRequiredAttributeValue(final Node nfinal String attName) {
        String ret = null;
        if (n != null && !StringHelper.isNullOrEmpty(attName)) {
            NamedNodeMap atts = n.getAttributes();
            Node att = atts.getNamedItem(attName);
            if (att == null) {
                throw new NullPointerException("Required attribute '" + attName
                        + "' not found in the node.");
            }
            if (att != null) {
                ret = att.getNodeValue();
            }
        }
        return ret;
    }

    
Return the first child of a node, regardless text node and CDATA sections

Parameters:
node
Returns:
    public static Node getFirstChild(final Node node) {
        Node result = node.getFirstChild();
        while (result != null
                && (result.getNodeType() == . || result.getNodeType() == .)) {
            result = result.getNextSibling();
        }
        return result;
    }

    
Return the next sibling of a node, regardless text node and CDATA sections

Parameters:
node
Returns:
The next sibling node, or null if node is null or no sibling node exists.
    public static Node getNextSibling(final Node node) {
        Node result = null;
        if (node != null) {
            result = node.getNextSibling();
            while (result != null
                    && (result.getNodeType() == . || result.getNodeType() == .)) {
                result = result.getNextSibling();
            }
        }
        return result;
    }

    
Return the text element of a node, even if it is contained in a CDATA section

Parameters:
node
Returns:
    public static String getTextContent(final Node node) {
        String result = null;
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node currentNode = list.item(i);
            if (currentNode.getNodeType() == .
                    || currentNode.getNodeType() == .) {
                result = currentNode.getNodeValue();
                Node nextSiblingNode = currentNode.getNextSibling();
                if (nextSiblingNode != null
                        && nextSiblingNode.getNodeType() == .) {
                    String cdataContent = nextSiblingNode.getNodeValue();
                    if (cdataContent != null) {
                        result = result + cdataContent;
                    }
                }
                result = result.replace('\t'' ').replace('\n'' ').trim();
                break;
            }
        }
        return result;
    }

    
Create a String result from a DOM document

Parameters:
document the DOM Document. Must not be null
Returns:
a String representation of the DOM Document
Throws:
javax.xml.transform.TransformerException
    public static String createStringFromDOMDocument(final Node document)
            throws TransformerException {
        return createStringFromDOMNode(documentfalse);
    }

    
Create a String result from a DOM Node

Parameters:
node the DOM Node. Must not be null
Returns:
a String representation of the DOM Document
Throws:
javax.xml.transform.TransformerException
    public static String createStringFromDOMNode(final Node nodethrows TransformerException {
        return createStringFromDOMNode(nodetrue);
    }

    
Create a java.lang.String from a Node list

Parameters:
list
Returns:
Throws:
javax.xml.transform.TransformerException
    public static String createStringFromDOMNodeList(final NodeList list)
            throws TransformerException {
        StringBuffer sb = new StringBuffer("");
        if (list != null) {
            for (int i = 0; i < list.getLength(); i++) {
                sb.append(createStringFromDOMNode(list.item(i)));
            }
        }
        return sb.toString();
    }

    
Create a String result from a DOM Node

Parameters:
node the DOM Node. Must not be null
Returns:
a String representation of the DOM Document
Throws:
javax.xml.transform.TransformerException
Parma:
moitDeclaration If true no XML declaration will be added.
    public static String createStringFromDOMNode(final Node nodefinal boolean omitDeclaration)
            throws TransformerException {
        node.normalize();
        final Source source = new DOMSource(node);
        final StringWriter out = new StringWriter();
        final Result resultStream = new StreamResult(out);
        final Transformer transformer;
        if (omitDeclaration) {
            transformer = Transformers.getXmlWithoutDeclarationTransformer();
        }
        else {
            transformer = Transformers.getXmlWithoutDeclarationTransformer();
        }
        try {
            transformer.transform(sourceresultStream);
        } finally {
            transformer.reset();
        }
        return out.toString();
    }

    
Create a document from a String

Parameters:
xml an xml string
Returns:
a org.w3c.dom.Document representing the document, null if an error occured
    public static Document createDocumentFromString(final String xml) {
        Document doc = null;
        try {
            InputStream in = new ByteArrayInputStream(xml.getBytes());
            InputSource inputSource = new InputSource(in);
            doc = DocumentBuilders.getNamespaceDocumentBuilder().parse(inputSource);
            doc.normalize();
        } catch (SAXException e) {
            .log(."Bad XML fragment can't be transformed to a DOM tree."e);
        } catch (IOException e) {
            .log(."Unexpected Error"e);
        }
        return doc;
    }

    
Return an array of String representing each Text element of the nodes which are in the list.

Parameters:
list
Returns:
    public static List<StringgetTextContents(final NodeList list) {
        List<Stringresult = null;
        if (list != null) {
            result = new ArrayList<String>();
            for (int i = 0; i < list.getLength(); i++) {
                Node pathElement = list.item(i);
                if (pathElement.getNodeType() != .) {
                    result.add(getTextContent(pathElement));
                }
            }
        }
        return result;
    }

    
Return the QName extracted from the targeted attribute of the given org.w3c.dom.Node

Parameters:
node the node from which attribute must be extracted
attrName name of the targeted attribute
Returns:
the javax.xml.namespace.QName value of the targeted org.w3c.dom.Node attribute, null if not found
Throws:
java.lang.IllegalArgumentException If the String does not conform to one of the following pattern : "localPart", "{ns}localPart" or "ns:localPart".
    public static QName extractXmlAttributeQName(final Node nodefinal String attrName) {
        String attr = XMLUtil.getAttributeValue(nodeattrName);
        QName qName = null;
        if (attr != null) {
            // qname like "xmlns:name"
            if ((attr.indexOf(':') > -1) && (attr.charAt(0) != '{')) {
                String ns = attr.substring(0, attr.indexOf(':'));
                String namespace = node.lookupNamespaceURI(ns);
                /*
                 * String namespace = source.getDocumentElement().getAttribute(
                 * "xmlns:" + ns);
                 */
                qName = new QName(namespaceattr.substring(attr.indexOf(':') + 1), ns);
            } else {
                // qname like "{ns}name" or "name"
                qName = QName.valueOf(attr);
            }
        }
        return qName;
    }

    
Extract the xml header charset encoding from the given xml String

Parameters:
msg the xml String
Returns:
the xml header charset encoding extrated from the given String or default encoding (UTF-8) if not found
    public static String extractXmlEncoding(String msg) {
        String xmlEncoding = ;
        if (msg.indexOf() > -1) {
            String xmlHeader = msg.substring(msg.indexOf(), msg
                    .indexOf() + 2);
            xmlHeader = StringHelper.replace(xmlHeader'"''\'');
            if (xmlHeader.indexOf() > -1) {
                ..println(xmlHeader);
                xmlEncoding = xmlHeader.substring(xmlHeader.indexOf()
                        + .length() + 2);
                xmlEncoding = xmlEncoding.substring(0, xmlEncoding.indexOf("'"));
            }
        }
        return xmlEncoding;
    }

    

Parameters:
node
attrName
Returns:
    public static QName extractRequiredXmlAttributeQName(final Node nodefinal String attrName) {
        String attr = XMLUtil.getRequiredAttributeValue(nodeattrName);
        QName qName = null;
        // qname like "xmlns:name"
        if ((attr.indexOf(':') > -1) && (attr.charAt(0) != '{')) {
            String ns = attr.substring(0, attr.indexOf(':'));
            String namespace = node.lookupNamespaceURI(ns);
            /*
             * String namespace = source.getDocumentElement().getAttribute(
             * "xmlns:" + ns);
             */
            qName = new QName(namespaceattr.substring(attr.indexOf(':') + 1), ns);
        } else {
            // qname like "{ns}name" or "name"
            qName = QName.valueOf(attr);
        }
        return qName;
    }

    
A List of Node that contains all children of this node; nodes must be of type Node.ELEMENT_NODE to be returned. If there are no children, this is a NodeList containing no nodes.

Parameters:
node the node from which children will be extracted
Returns:
a List of child Node of type Node.ELEMENT_NODE
    public static List<NodegetNodeChildren(final Node node) {
        List<Nodechildren = new ArrayList<Node>();
        if (node != null) {
            NodeList childrenList = node.getChildNodes();
            for (int i = 0; i < childrenList.getLength(); i++) {
                Node child = childrenList.item(i);
                if (child.getNodeType() == .) {
                    children.add(child);
                }
            }
        }
        return children;
    }

    

Parameters:
document
elementName
Returns:
the first matching node, null otherwise, or if document/path is null
    public static Node getNode(Document documentString elementName) {
        Node result = null;
        if (document != null && elementName != null) {
            NodeList resList = document.getElementsByTagName(elementName);
            if (resList != null && resList.getLength() > 0) {
                return resList.item(0);
            }
        }
        return result;
    }

    

Parameters:
document
elementName
attributeName
attributeValue
Returns:
the first matching node, null otherwise, or if document/path is null
    public static Node getNodeWithAttribute(Document documentString elementName,
            String attributeNameString attributeValue) {
        Node result = null;
        if (document != null && elementName != null && attributeName != null
                && attributeValue != null) {
            NodeList resList = document.getElementsByTagName(elementName);
            for (int i = 0; i < resList.getLength() && result == nulli++) {
                Element curNode = (ElementresList.item(i);
                if (attributeValue.equals(curNode.getAttribute(attributeName))) {
                    result = curNode;
                }
            }
        }
        return result;
    }

    
Write a document to an output stream. The output stream and the document must not be null.

Parameters:
document
outputFile
    public static void writeDocument(final Document documentfinal OutputStream outputStream)
            throws Exception {
        if (document != null && outputStream != null) {
            final Transformer transformer = Transformers.getXmlWithoutDeclarationTransformer();
            try {
                transformer.transform(new DOMSource(document), new StreamResult(outputStream));
            } finally {
                transformer.reset();
            }
        } else {
            throw new Exception("Can not write document to output stream");
        }
    }

    
Load a document from an input stream.

Parameters:
inputStream
Returns:
Throws:
java.io.IOException
org.xml.sax.SAXException
    public static Document loadDocument(InputStream inputStreamthrows IOExceptionSAXException {
        Document document = null;
        try {
            document = DocumentBuilders.getNamespaceDocumentBuilder().parse(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return document;
    }
    
    
Get a new document

Returns:
    public static Document createDocument() {
        return DocumentBuilders.getNamespaceDocumentBuilder().newDocument();
    }
New to GrepCode? Check out our FAQ X