Example usage for org.w3c.dom Document createDocumentFragment

List of usage examples for org.w3c.dom Document createDocumentFragment

Introduction

In this page you can find the example usage for org.w3c.dom Document createDocumentFragment.

Prototype

public DocumentFragment createDocumentFragment();

Source Link

Document

Creates an empty DocumentFragment object.

Usage

From source file:com.portfolio.data.utils.DomUtils.java

private static void insererXML(Connection connexion, Document xmlSourceDoc, String partageableId,
        StringBuffer outTrace, boolean trace) throws Exception {
    //  ---------------------------------------------------
    if (trace)// w w  w .j a v a2 s.c o m
        outTrace.append("<br>insererPartageable -- entre");
    if (trace)
        outTrace.append("<br>partageableId=" + partageableId);
    // ===============chargement du document source ========================================

    if (trace)
        outTrace.append("<br>lecture du document xml :" + partageableId + "...");
    Document xmlPartageable = buildDOM(readXmlString(connexion, partageableId, outTrace));
    if (trace)
        outTrace.append(" ok");

    DocumentFragment aInserer = xmlSourceDoc.createDocumentFragment();

    NodeList liste = xmlPartageable.getDocumentElement().getChildNodes();
    int nbListe = liste.getLength();
    if (trace)
        outTrace.append("<br> nbListe=" + nbListe);
    for (int i = 0; i < nbListe; i++) {
        aInserer.appendChild(xmlSourceDoc.importNode(liste.item(i), true));
    }

    xmlSourceDoc.getFirstChild().insertBefore(aInserer, xmlSourceDoc.getFirstChild().getFirstChild());
    if (trace)
        outTrace.append("<br>insererPartageable -- sortie");
}

From source file:org.callimachusproject.server.RoundTripTest.java

public void testSingleDocumentFragment() throws Exception {
    DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
    Document doc = builder.newDocumentBuilder().newDocument();
    DocumentFragment frag = doc.createDocumentFragment();
    frag.appendChild(doc.createElement("root"));
    trip.documentFragment(frag);//from www .j  a  v a2  s  .c  om
    assertEquals(null, trip.documentFragment(null));
}

From source file:org.callimachusproject.server.RoundTripTest.java

public void testSetOfSingleDocumentFragment() throws Exception {
    DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
    Document doc = builder.newDocumentBuilder().newDocument();
    DocumentFragment frag = doc.createDocumentFragment();
    frag.appendChild(doc.createElement("root"));
    trip.setOfDocumentFragment(singleton(frag));
    assertEquals(EMPTY_SET, trip.setOfDocumentFragment(EMPTY_SET));
}

From source file:org.callimachusproject.server.RoundTripTest.java

public void testDocumentFragment() throws Exception {
    DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
    Document doc = builder.newDocumentBuilder().newDocument();
    DocumentFragment frag = doc.createDocumentFragment();
    frag.appendChild(doc.createElement("root1"));
    frag.appendChild(doc.createElement("root2"));
    trip.documentFragment(frag);//from   w  ww .j a v  a  2s. com
    assertEquals(null, trip.documentFragment(null));
}

From source file:org.callimachusproject.server.RoundTripTest.java

public void testSetOfDocumentFragment() throws Exception {
    DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
    Document doc = builder.newDocumentBuilder().newDocument();
    DocumentFragment frag = doc.createDocumentFragment();
    frag.appendChild(doc.createElement("root1"));
    frag.appendChild(doc.createElement("root2"));
    trip.setOfDocumentFragment(singleton(frag));
    assertEquals(EMPTY_SET, trip.setOfDocumentFragment(EMPTY_SET));
}

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Get the author affiliations for a given article
 * @param doc article xml/* w w w .j  a  v  a2  s.  c  om*/
 * @param doc article xml
 * @return author affiliations
 */
public ArrayList<AuthorExtra> getAuthorAffiliations(Document doc) {

    ArrayList<AuthorExtra> list = new ArrayList<AuthorExtra>();
    Map<String, String> affiliateMap = new HashMap<String, String>();

    if (doc == null) {
        return list;
    }

    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();

        XPathExpression affiliationListExpr = xpath.compile("//aff");
        XPathExpression affiliationAddrExpr = xpath.compile("//addr-line");

        NodeList affiliationNodeList = (NodeList) affiliationListExpr.evaluate(doc, XPathConstants.NODESET);

        // Map all affiliation id's to their affiliation strings
        for (int i = 0; i < affiliationNodeList.getLength(); i++) {
            Node node = affiliationNodeList.item(i);
            // Not all <aff>'s have the 'id' attribute.
            String id = (node.getAttributes().getNamedItem("id") == null) ? ""
                    : node.getAttributes().getNamedItem("id").getTextContent();
            // Not all <aff> id's are affiliations.
            if (id.startsWith("aff")) {
                DocumentFragment df = doc.createDocumentFragment();
                df.appendChild(node);
                String address = ((Node) affiliationAddrExpr.evaluate(df, XPathConstants.NODE))
                        .getTextContent();
                affiliateMap.put(id, address);
            }
        }

        XPathExpression authorExpr = xpath.compile("//contrib-group/contrib[@contrib-type='author']");
        XPathExpression surNameExpr = xpath.compile("//name/surname");
        XPathExpression givenNameExpr = xpath.compile("//name/given-names");
        XPathExpression affExpr = xpath.compile("//xref[@ref-type='aff']");

        NodeList authorList = (NodeList) authorExpr.evaluate(doc, XPathConstants.NODESET);

        for (int i = 0; i < authorList.getLength(); i++) {
            Node cnode = authorList.item(i);
            DocumentFragment df = doc.createDocumentFragment();
            df.appendChild(cnode);
            Node sNode = (Node) surNameExpr.evaluate(df, XPathConstants.NODE);
            Node gNode = (Node) givenNameExpr.evaluate(df, XPathConstants.NODE);

            // Either surname or givenName can be blank
            String surname = (sNode == null) ? "" : sNode.getTextContent();
            String givenName = (gNode == null) ? "" : gNode.getTextContent();
            // If both are null then don't bother to add
            if ((sNode != null) || (gNode != null)) {
                NodeList affList = (NodeList) affExpr.evaluate(df, XPathConstants.NODESET);
                ArrayList<String> affiliations = new ArrayList<String>();

                // Build a list of affiliations for this author
                for (int j = 0; j < affList.getLength(); j++) {
                    Node anode = affList.item(j);
                    String affId = anode.getAttributes().getNamedItem("rid").getTextContent();
                    affiliations.add(affiliateMap.get(affId));
                }

                AuthorExtra authorEx = new AuthorExtra();
                authorEx.setAuthorName(surname, givenName);
                authorEx.setAffiliations(affiliations);
                list.add(authorEx);
            }
        }
    } catch (Exception e) {
        log.error("Error occurred while gathering the author affiliations.", e);
    }

    return list;
}

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Get references for a given article/*  w  w  w .j  a  v a 2  s  .c o  m*/
 * @param doc article xml
 * @return references
 */
public ArrayList<CitationReference> getReferences(Document doc) {
    ArrayList<CitationReference> list = new ArrayList<CitationReference>();

    if (doc == null) {
        return list;
    }

    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//back/ref-list[title='References']/ref");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList refList = (NodeList) result;

        if (refList.getLength() == 0) {
            expr = xpath.compile("//back/ref-list/ref");
            result = expr.evaluate(doc, XPathConstants.NODESET);
            refList = (NodeList) result;
        }

        XPathExpression typeExpr = xpath.compile("//citation | //nlm-citation");
        XPathExpression titleExpr = xpath.compile("//article-title");
        XPathExpression authorsExpr = xpath.compile("//person-group[@person-group-type='author']/name");
        XPathExpression journalExpr = xpath.compile("//source");
        XPathExpression volumeExpr = xpath.compile("//volume");
        XPathExpression numberExpr = xpath.compile("//label");
        XPathExpression fPageExpr = xpath.compile("//fpage");
        XPathExpression lPageExpr = xpath.compile("//lpage");
        XPathExpression yearExpr = xpath.compile("//year");
        XPathExpression publisherExpr = xpath.compile("//publisher-name");

        for (int i = 0; i < refList.getLength(); i++) {

            Node refNode = refList.item(i);
            CitationReference citation = new CitationReference();

            DocumentFragment df = doc.createDocumentFragment();
            df.appendChild(refNode);

            // citation type
            Object resultObj = typeExpr.evaluate(df, XPathConstants.NODE);
            Node resultNode = (Node) resultObj;
            if (resultNode != null) {
                NamedNodeMap nnm = resultNode.getAttributes();
                Node nnmNode = nnm.getNamedItem("citation-type");
                // some old articles do not have this attribute
                if (nnmNode != null) {
                    citation.setCitationType(nnmNode.getTextContent());
                }
            }

            // title
            resultObj = titleExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setTitle(resultNode.getTextContent());
            }

            // authors
            resultObj = authorsExpr.evaluate(df, XPathConstants.NODESET);
            NodeList resultNodeList = (NodeList) resultObj;
            ArrayList<String> authors = new ArrayList<String>();
            for (int j = 0; j < resultNodeList.getLength(); j++) {
                Node nameNode = resultNodeList.item(j);
                NodeList namePartList = nameNode.getChildNodes();
                String surName = "";
                String givenName = "";
                for (int k = 0; k < namePartList.getLength(); k++) {
                    Node namePartNode = namePartList.item(k);
                    if (namePartNode.getNodeName().equals("surname")) {
                        surName = namePartNode.getTextContent();
                    } else if (namePartNode.getNodeName().equals("given-names")) {
                        givenName = namePartNode.getTextContent();
                    }
                }
                authors.add(givenName + " " + surName);
            }

            citation.setAuthors(authors);

            // journal title
            resultObj = journalExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setJournalTitle(resultNode.getTextContent());
            }

            // volume
            resultObj = volumeExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setVolume(resultNode.getTextContent());
            }

            // citation number
            resultObj = numberExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setNumber(resultNode.getTextContent());
            }

            // citation pages
            String firstPage = null;
            String lastPage = null;
            resultObj = fPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                firstPage = resultNode.getTextContent();
            }

            resultObj = lPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                lastPage = resultNode.getTextContent();
            }

            if (firstPage != null) {
                if (lastPage != null) {
                    citation.setPages(firstPage + "-" + lastPage);
                } else {
                    citation.setPages(firstPage);
                }
            }

            // citation year
            resultObj = yearExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setYear(resultNode.getTextContent());
            }

            // citation publisher
            resultObj = publisherExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setPublisher(resultNode.getTextContent());
            }

            list.add(citation);
        }

    } catch (Exception e) {
        log.error("Error occurred while gathering the citation references.", e);
    }

    return list;

}

From source file:org.ambraproject.service.article.FetchArticleServiceImpl.java

/**
 * Get references for a given article/*from   ww w. j  a  va2 s .  co m*/
 *
 * @param doc article xml
 * @return references
 */
public ArrayList<CitationReference> getReferences(Document doc) {
    ArrayList<CitationReference> list = new ArrayList<CitationReference>();

    if (doc == null) {
        return list;
    }

    try {
        NodeList refList = getReferenceNodes(doc);

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();

        XPathExpression typeExpr = xpath.compile("//citation | //nlm-citation | //element-citation");
        XPathExpression titleExpr = xpath.compile("//article-title");
        XPathExpression authorsExpr = xpath.compile("//person-group[@person-group-type='author']/name");
        XPathExpression journalExpr = xpath.compile("//source");
        XPathExpression volumeExpr = xpath.compile("//volume");
        XPathExpression numberExpr = xpath.compile("//label");
        XPathExpression fPageExpr = xpath.compile("//fpage");
        XPathExpression lPageExpr = xpath.compile("//lpage");
        XPathExpression yearExpr = xpath.compile("//year");
        XPathExpression publisherExpr = xpath.compile("//publisher-name");

        for (int i = 0; i < refList.getLength(); i++) {

            Node refNode = refList.item(i);
            CitationReference citation = new CitationReference();

            DocumentFragment df = doc.createDocumentFragment();
            df.appendChild(refNode);

            // citation type
            Object resultObj = typeExpr.evaluate(df, XPathConstants.NODE);
            Node resultNode = (Node) resultObj;
            if (resultNode != null) {
                String citationType = getCitationType(resultNode);
                if (citationType != null) {
                    citation.setCitationType(citationType);
                }
            }

            // title
            resultObj = titleExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setTitle(resultNode.getTextContent());
            }

            // authors
            resultObj = authorsExpr.evaluate(df, XPathConstants.NODESET);
            NodeList resultNodeList = (NodeList) resultObj;
            ArrayList<String> authors = new ArrayList<String>();
            for (int j = 0; j < resultNodeList.getLength(); j++) {
                Node nameNode = resultNodeList.item(j);
                NodeList namePartList = nameNode.getChildNodes();
                String surName = "";
                String givenName = "";
                for (int k = 0; k < namePartList.getLength(); k++) {
                    Node namePartNode = namePartList.item(k);
                    if (namePartNode.getNodeName().equals("surname")) {
                        surName = namePartNode.getTextContent();
                    } else if (namePartNode.getNodeName().equals("given-names")) {
                        givenName = namePartNode.getTextContent();
                    }
                }
                authors.add(givenName + " " + surName);
            }

            citation.setAuthors(authors);

            // journal title
            resultObj = journalExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setJournalTitle(resultNode.getTextContent());
            }

            // volume
            resultObj = volumeExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setVolume(resultNode.getTextContent());
            }

            // citation number
            resultObj = numberExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setNumber(resultNode.getTextContent());
            }

            // citation pages
            String firstPage = null;
            String lastPage = null;
            resultObj = fPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                firstPage = resultNode.getTextContent();
            }

            resultObj = lPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                lastPage = resultNode.getTextContent();
            }

            if (firstPage != null) {
                if (lastPage != null) {
                    citation.setPages(firstPage + "-" + lastPage);
                } else {
                    citation.setPages(firstPage);
                }
            }

            // citation year
            resultObj = yearExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setYear(resultNode.getTextContent());
            }

            // citation publisher
            resultObj = publisherExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setPublisher(resultNode.getTextContent());
            }

            list.add(citation);
        }

    } catch (Exception e) {
        log.error("Error occurred while gathering the citation references.", e);
    }

    return list;

}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Get a document fragment from a <code>Reader</code>.
 * The reader must provide valid XML, but it is allowed that the XML
 * has more than one root node. This xml is parsed by the
 * specified parser instance and a DOM DocumentFragment is created.
 *//* w  w w  . j a  v  a  2  s. c o  m*/
public static DocumentFragment getDocumentFragment(SAXParser parser, Reader stream) throws ProcessingException {
    DocumentFragment frag = null;

    Writer writer;
    Reader reader;
    boolean removeRoot = true;

    try {
        // create a writer,
        // write the root element, then the input from the
        // reader
        writer = new StringWriter();

        writer.write(XML_ROOT_DEFINITION);
        char[] cbuf = new char[16384];
        int len;
        do {
            len = stream.read(cbuf, 0, 16384);
            if (len != -1) {
                writer.write(cbuf, 0, len);
            }
        } while (len != -1);
        writer.write("</root>");

        // now test if xml input start with <?xml
        String xml = writer.toString();
        String searchString = XML_ROOT_DEFINITION + "<?xml ";
        if (xml.startsWith(searchString) == true) {
            // now remove the surrounding root element
            xml = xml.substring(XML_ROOT_DEFINITION.length(), xml.length() - 7);
            removeRoot = false;
        }

        reader = new StringReader(xml);

        InputSource input = new InputSource(reader);

        DOMBuilder builder = new DOMBuilder();
        builder.startDocument();
        builder.startElement("", "root", "root", XMLUtils.EMPTY_ATTRIBUTES);

        IncludeXMLConsumer filter = new IncludeXMLConsumer(builder, builder);
        parser.parse(input, filter);

        builder.endElement("", "root", "root");
        builder.endDocument();

        // Create Document Fragment, remove <root>
        final Document doc = builder.getDocument();
        frag = doc.createDocumentFragment();
        final Node root = doc.getDocumentElement().getFirstChild();
        root.normalize();
        if (removeRoot == false) {
            root.getParentNode().removeChild(root);
            frag.appendChild(root);
        } else {
            Node child;
            while (root.hasChildNodes() == true) {
                child = root.getFirstChild();
                root.removeChild(child);
                frag.appendChild(child);
            }
        }
    } catch (SAXException sax) {
        throw new ProcessingException("SAXException: " + sax, sax);
    } catch (IOException ioe) {
        throw new ProcessingException("IOException: " + ioe, ioe);
    }
    return frag;
}

From source file:org.apache.ode.jbi.EndpointReferenceContextImpl.java

public EndpointReference resolveEndpointReference(Element epr) {
    QName elname = new QName(epr.getNamespaceURI(), epr.getLocalName());

    if (__log.isDebugEnabled()) {
        __log.debug("resolveEndpointReference:\n" + prettyPrint(epr));
    }/*from   w  w  w  .ja  v a 2 s .  com*/
    if (!elname.equals(EndpointReference.SERVICE_REF_QNAME))
        throw new IllegalArgumentException(
                "EPR root element " + elname + " should be " + EndpointReference.SERVICE_REF_QNAME);

    Document doc = DOMUtils.newDocument();
    DocumentFragment fragment = doc.createDocumentFragment();
    NodeList children = epr.getChildNodes();
    for (int i = 0; i < children.getLength(); ++i)
        if (children.item(i) instanceof Element)
            fragment.appendChild(doc.importNode(children.item(i), true));
    ServiceEndpoint se = _ode.getContext().resolveEndpointReference(fragment);
    if (se == null)
        return null;
    return new JbiEndpointReference(se);
}