001    /*
002     * To change this template, choose Tools | Templates
003     * and open the template in the editor.
004     */
005    package org.biojava3.core.util;
006    
007    import static org.biojava3.core.sequence.io.util.IOUtils.close;
008    import static org.biojava3.core.sequence.io.util.IOUtils.openFile;
009    
010    import java.io.BufferedInputStream;
011    import java.io.File;
012    import java.io.InputStream;
013    import java.io.OutputStream;
014    import java.util.ArrayList;
015    
016    import javax.xml.parsers.DocumentBuilder;
017    import javax.xml.parsers.DocumentBuilderFactory;
018    import javax.xml.transform.Transformer;
019    import javax.xml.transform.TransformerFactory;
020    import javax.xml.transform.dom.DOMSource;
021    import javax.xml.transform.stream.StreamResult;
022    import javax.xml.xpath.XPath;
023    import javax.xml.xpath.XPathConstants;
024    import javax.xml.xpath.XPathFactory;
025    
026    import org.w3c.dom.Document;
027    import org.w3c.dom.Element;
028    import org.w3c.dom.Node;
029    import org.w3c.dom.NodeList;
030    
031    /**
032     *
033     * @author Scooter
034     */
035    public class XMLHelper {
036    
037        static public Element addChildElement(Element parentElement, String elementName) {
038            Element childElement = parentElement.getOwnerDocument().createElement(elementName);
039            parentElement.appendChild(childElement);
040            return childElement;
041        }
042    
043        static public Document getNewDocument() throws Exception {
044    
045            //Create instance of DocumentBuilderFactory
046            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
047            //Get the DocumentBuilder
048            DocumentBuilder docBuilder = factory.newDocumentBuilder();
049            //Create blank DOM Document
050            Document doc = docBuilder.newDocument();
051            return doc;
052        }
053    
054        static public Document loadXML(String fileName) throws Exception {
055            InputStream is = openFile(new File(fileName));
056            Document doc = inputStreamToDocument(new BufferedInputStream(is));
057            close(is);
058            return doc;
059        }
060    
061        static public Document inputStreamToDocument(InputStream inputStream) throws Exception {
062            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
063    
064            DocumentBuilder db = dbf.newDocumentBuilder();
065    
066            Document doc = db.parse(inputStream);
067            doc.getDocumentElement().normalize();
068    
069            return doc;
070        }
071    
072        static public void outputToStream(Document document, OutputStream outputStream) throws Exception {
073            // Use a Transformer for output
074            TransformerFactory tFactory = TransformerFactory.newInstance();
075            Transformer transformer = tFactory.newTransformer();
076            //    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
077    
078            DOMSource source = new DOMSource(document);
079            StreamResult result = new StreamResult(outputStream);
080            transformer.transform(source, result);
081    
082    
083        }
084    
085        static public void outputToStream(Element document, OutputStream outputStream) throws Exception {
086            // Use a Transformer for output
087            TransformerFactory tFactory = TransformerFactory.newInstance();
088            Transformer transformer = tFactory.newTransformer();
089            //     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
090    
091            DOMSource source = new DOMSource(document);
092            StreamResult result = new StreamResult(outputStream);
093            transformer.transform(source, result);
094    
095        }
096        //static XPath xpath = XPathFactory.newInstance().newXPath();
097    
098        static public Element selectParentElement(Element element, String parentName) {
099            Element parentElement = (Element) element.getParentNode();
100            if (parentElement == null) {
101                return null;
102            }
103            if (parentElement.getTagName().equals(parentName)) {
104                return parentElement;
105            }
106            return selectParentElement(parentElement, parentName);
107        }
108    
109        static public Element selectSingleElement(Element element, String xpathExpression) throws Exception {
110            if (xpathExpression.indexOf("/") == -1) {
111                NodeList nodeList = element.getChildNodes();
112                for (int i = 0; i < nodeList.getLength(); i++) {
113                    Node node = nodeList.item(i);
114                    if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) {
115                        return (Element) node;
116                    }
117                }
118                //  NodeList nodes = element.getElementsByTagName(xpathExpression);
119                //  if (nodes.getLength() > 0) {
120                //      return (Element) nodes.item(0);
121                //  } else {
122                return null;
123                //  }
124            } else {
125                XPath xpath = XPathFactory.newInstance().newXPath();
126                Element node = (Element) xpath.evaluate(xpathExpression, element, XPathConstants.NODE);
127                return node;
128            }
129        }
130    
131        static public ArrayList<Element> selectElements(Element element, String xpathExpression) throws Exception {
132            ArrayList<Element> resultVector = new ArrayList<Element>();
133            if (element == null) {
134                return resultVector;
135            }
136            if (xpathExpression.indexOf("/") == -1) {
137                NodeList nodeList = element.getChildNodes();
138                for (int i = 0; i < nodeList.getLength(); i++) {
139                    Node node = nodeList.item(i);
140                    if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) {
141                        resultVector.add((Element) node);
142                    }
143                }
144            } else {
145                XPath xpath = XPathFactory.newInstance().newXPath();
146                NodeList nodes = (NodeList) xpath.evaluate(xpathExpression, element, XPathConstants.NODESET);
147    
148    
149                for (int i = 0; i < nodes.getLength(); i++) {
150                    Node node = nodes.item(i);
151                    resultVector.add((Element) node);
152                }
153            }
154            return resultVector;
155        }
156    }