Example usage for org.dom4j Node asXML

List of usage examples for org.dom4j Node asXML

Introduction

In this page you can find the example usage for org.dom4j Node asXML.

Prototype

String asXML();

Source Link

Document

asXML returns the textual XML representation of this node.

Usage

From source file:com.cladonia.xml.viewer.XmlElementNode.java

License:Mozilla Public License

private String getContent(XElement elem) {
    Iterator iterator = elem.nodeIterator();
    StringBuffer buf = new StringBuffer();

    while (iterator.hasNext()) {
        Node node = (Node) iterator.next();
        if (node instanceof Text) {
            buf.append(node.asXML());
        }// ww  w .j  a  v a  2 s.  c  o  m
    }

    return buf.toString().trim();
}

From source file:com.cladonia.xml.xdiff.XmlElementNode.java

License:Open Source License

/**
 * Constructs the the XML element node./*  w w  w.  j a va 2  s  .  com*/
 *
 * @param element the XML element.
 */
public XmlElementNode(XElement element, boolean end, XmlElementNode parent) {

    this.element = element;
    this.parent = parent;

    isEndTag = end;
    format();

    if (!isEndTag()) {

        List childNodes = element.content();

        for (int i = 0; i < element.nodeCount(); i++) {
            Node node = element.node(i);

            if (node instanceof XElement) {
                add(new XmlElementNode((XElement) node, this));
            } else if ((node instanceof Text) && isMixedElementAndContent(element) && !isWhiteSpace(node)) {

                if (i < element.nodeCount()) {
                    Node nextNode = element.node(i + 1);
                    if (nextNode instanceof ProcessingInstruction) {
                        add(new XmlTextNode((Text) node, (ProcessingInstruction) nextNode, this));
                    } else {
                        // can't be PI after it
                        add(new XmlTextNode((Text) node, this));
                    }
                }

                //                  if (i<element.nodeCount())
                //                  {
                //                     Node nextNode = element.node(i+1);
                //                     if (nextNode instanceof ProcessingInstruction)
                //                     {
                //                        add( new XmlTextNode((Text)node,(ProcessingInstruction)nextNode,this));
                //                     }
                //                     else if (nextNode instanceof Text)
                //                     {
                //                        //   append the node and check for the next one
                //                        String combined = node.asXML().trim()+" "+nextNode.asXML().trim();
                //                        i++;
                //                        while (i<element.nodeCount())
                //                        {
                //                           Node nextNextNode = element.node(i+1);
                //                           if (nextNextNode instanceof Text)
                //                           {
                //                              // combine
                //                              combined = combined+" "+nextNextNode.asXML().trim();
                //                              i++;
                //                           }
                //                           else
                //                              break;
                //                        }
                //                        
                //                        if (i< element.nodeCount())
                //                        {
                //                           Node nextNextNode = element.node(i+1);
                //                           if (nextNextNode instanceof ProcessingInstruction)
                //                           {
                //                              add( new XmlTextNode(combined,(ProcessingInstruction)nextNextNode,this));
                //                           }
                //                           else
                //                           {
                //                              add( new XmlTextNode(combined,this,false));
                //                           }
                //                        }
                //                        else
                //                        {
                //                           add( new XmlTextNode(combined,this,false));
                //                        }
                //                     }
                //                     else
                //                     {
                //                        // can't be PI after it
                //                        add( new XmlTextNode((Text)node,this));
                //                     }
                //                  }
                //                  else
                //                  {
                //                     // can't be PI after it
                //                     add( new XmlTextNode((Text)node,this));
                //                  }

            } else if ((node instanceof ProcessingInstruction) && isMixedElementAndContent(element)) {
                String pi = node.asXML();
                if (pi.startsWith(DELETE)) {
                    // check for mixed delete which we treat as a change
                    if (pi.indexOf("\"") != -1 && pi.lastIndexOf(MIXED_DELETE_PI_END) != -1) {
                        String updateTextFrom = getUpdatePIValue(pi);

                        DefaultText dummy = new DefaultText("");
                        childNodes.add(i + 1, dummy);

                        add(new XmlTextNode(dummy, updateTextFrom, this, true));
                    }
                }
            }
        }

        List elements = element.elements();
        // create an end node...   
        if (elements != null && elements.size() > 0) {
            add(new XmlElementNode(element, true, this));
        }
    }

    //format();

}

From source file:com.cladonia.xml.xdiff.XmlElementNode.java

License:Open Source License

private void parseDiffPIs(XElement element) {
    boolean updateFromFound = false;

    for (int i = 0; i < element.nodeCount(); i++) {
        Node node = element.node(i);

        if (node instanceof ProcessingInstruction) {
            String pi = node.asXML();

            if (pi.startsWith(UPDATEFROM)) {
                // element update
                if (updateFromFound == false) {
                    updateElementFrom = getUpdatePIValue(pi);
                    updateFromFound = true;
                } else {
                    // here before, probably mixed content
                    updateElementFrom += " " + getUpdatePIValue(pi);
                }/*from w w w  .  j ava 2s . c  o m*/
                setDiffIcon();
            } else if (pi.startsWith(UPDATE)) {
                // attribute update
                updateAttributes = getUpdateAttributeTable();
                String attrName = getUpdateAttrName(pi);
                String attrValue = getUpdatePIValue(pi);

                updateAttributes.put(attrName, attrValue);
                setDiffIcon();
            } else if (pi.startsWith(INSERT)) {
                // check for mixed insert which we treat as a change
                if (pi.equals(MIXED_INSERT)) {
                    updateElementFrom = "";
                } else {
                    // element or attribute?
                    String name = getPIName(pi);

                    if (element.getQualifiedName().equals(name)) {
                        // element insert
                        insertElement = true;
                    } else {
                        // attribute insert
                        insertAttributes = getInsertAttributes();
                        insertAttributes.add(name);
                    }
                }

                setDiffIcon();
            } else if (pi.startsWith(DELETE)) {
                // check for mixed delete which we treat as a change
                if (pi.indexOf("\"") != -1 && pi.lastIndexOf(MIXED_DELETE_PI_END) != -1) {
                    updateElementFrom = getUpdatePIValue(pi);
                } else {

                    //element or attribute?
                    String name = getPIName(pi);

                    if (element.getQualifiedName().equals(name)) {
                        // element delete
                        deleteElement = true;
                    } else {
                        // attribute delete
                        deleteAttributes = getDeleteAttributes();
                        deleteAttributes.add(name);
                    }
                }

                setDiffIcon();
            }
        }
    }
}

From source file:com.devoteam.srit.xmlloader.core.Parameter.java

License:Open Source License

public void applyXPath(String xml, String xpath, boolean deleteNS) throws Exception {
    // remove beginning to '<' character
    int iPosBegin = xml.indexOf('<');
    if (iPosBegin > 0) {
        xml = xml.substring(iPosBegin);/*from w w w . ja v a  2s.  c  om*/
    }
    // remove from '>' character to the end
    int iPosEnd = xml.lastIndexOf('>');
    if ((iPosEnd > 0) && (iPosEnd < xml.length() - 1)) {
        xml = xml.substring(0, iPosEnd + 1);
    }

    int iPosXMLLine = xml.indexOf("<?xml");
    if (iPosXMLLine < 0) {
        xml = "<?xml version='1.0'?>" + xml;
    }

    // remove the namespace because the parser does not support them if there are not declare in the root node
    if (deleteNS) {
        xml = xml.replaceAll("<[a-zA-Z\\.0-9_]+:", "<");
        xml = xml.replaceAll("</[a-zA-Z\\.0-9_]+:", "</");
    }
    // remove doctype information (dtd files for the XML syntax)
    xml = xml.replaceAll("<!DOCTYPE\\s+\\w+\\s+\\w+\\s+[^>]+>", "");

    InputStream input = new ByteArrayInputStream(xml.getBytes());
    SAXReader reader = new SAXReader(false);
    reader.setEntityResolver(new XMLLoaderEntityResolver());
    Document document = reader.read(input);

    XPath xpathObject = document.createXPath(xpath);
    Object obj = xpathObject.evaluate(document.getRootElement());

    if (obj instanceof List) {
        List<Node> list = (List<Node>) obj;
        for (Node node : list) {
            add(node.asXML());
        }
    } else if (obj instanceof DefaultElement) {
        Node node = (Node) obj;
        add(node.asXML());
    } else if (obj instanceof DefaultAttribute) {
        Node node = (Node) obj;
        add(node.getStringValue());
    } else if (obj instanceof DefaultText) {
        Node node = (Node) obj;
        add(node.getText());
    } else {
        add(obj.toString());
    }
}

From source file:com.dotmarketing.viewtools.XmlTool.java

License:Apache License

/**
 * If this instance has no XML {@link Node}s, then this returns the result of {@code super.toString()}. Otherwise,
 * it returns the XML (as a string) of all the internally held nodes that are not {@link Attribute}s. For
 * attributes, only the value is used.//from  w w w . j  av a 2s.co m
 */
public String toString() {
    if (isEmpty()) {
        return super.toString();
    }
    StringBuilder out = new StringBuilder();
    for (Node n : nodes) {
        if (n instanceof Attribute) {
            out.append(n.getText().trim());
        } else {
            out.append(n.asXML());
        }
    }
    return out.toString();
}

From source file:com.globalsight.everest.edit.offline.ttx.TTXParser.java

License:Apache License

/**
 * Parse offline uploading TTX file for uploading purpose.
 * /*from  ww w. ja  va2 s. com*/
 * @param doc
 * @param isParsingTTXForGS
 *            :True for GS uploading;False for common TTX file parsing.
 * @return
 * @throws Exception
 */
public String parseToTxt(Document doc, boolean isParsingTTXForGS) throws Exception {
    this.isParsingTTXForGS = isParsingTTXForGS;

    Element root = doc.getRootElement();// TRADOStag element
    // toolSettings
    parseToolSettings(root);

    // userSettings
    parseUserSettings(root);

    Element bodyElement = root.element(TTXConstants.BODY);
    Element rawElement = bodyElement.element(TTXConstants.RAW);
    // parse header info such as "pageId","taskId" etc.
    parseHeaderInfo(rawElement);
    // append header info
    appendHeaderInfo();

    // main contents
    if (rawElement.nodeCount() > 0) {
        Iterator nodesIt = rawElement.nodeIterator();
        while (nodesIt.hasNext()) {
            Node node = (Node) nodesIt.next();
            String nodeStr = node.asXML();
            domNodehandler(node, false);
        }
    }

    appendEndInfo();

    return results.toString();
}

From source file:com.globalsight.everest.edit.offline.ttx.TTXParser.java

License:Apache License

private void elementNodeProcessor(Node p_node, boolean p_isSource) {
    Element element = (Element) p_node;
    String eleStr = element.asXML();
    String elementName = element.getName();

    boolean isHeaderInfoUT = false;
    boolean isTuId = false;
    if (TTXConstants.TU.equalsIgnoreCase(elementName) || (element.getParent() != null
            && TTXConstants.TUV.equalsIgnoreCase(element.getParent().getName()))) {
        // latestPosition = TTXConstants.IN_TU;
    } else if (TTXConstants.UT.equalsIgnoreCase(elementName)) {
        Attribute att = element.attribute(TTXConstants.UT_ATT_DISPLAYTEXT);
        if (att != null) {
            String value = att.getValue();
            // If header info,return as header info has been handled
            // separately.
            // This check is not required.
            isHeaderInfoUT = isHeaderInfo(value);
            if (isHeaderInfoUT) {
                return;
            }/*from   w w w . j  a  v  a2 s  . c  om*/
            // If TuId,handle them here.
            isTuId = isTuId(value);
            if (isTuId) {
                // latestPosition = TTXConstants.TU_ID;
                String tuId = value.substring(value.indexOf(":") + 1).trim();
                if (results != null && results.length() > 0) {
                    results.append(TTXConstants.NEW_LINE).append(TTXConstants.NEW_LINE);
                }
                results.append(TTXConstants.HASH_MARK).append(tuId).append(TTXConstants.NEW_LINE);

                return;
            }
        }
    }

    if (element.nodeCount() > 0) {
        Iterator nodesIt = element.nodeIterator();
        while (nodesIt.hasNext()) {
            Node node = (Node) nodesIt.next();
            String nodeStr = node.asXML();
            String nodeName = node.getName();
            if (TTXConstants.TUV.equalsIgnoreCase(node.getName())) {
                Attribute langAtt = ((Element) node).attribute(TTXConstants.TUV_ATT_LANG);
                String lang = null;
                if (langAtt != null) {
                    lang = langAtt.getValue();
                }
                if (sourceLanguage != null && sourceLanguage.equals(lang)) {
                    // latestPosition = TTXConstants.IN_SOURCE_TUV;
                    // Not handle source TUV for TTX off-line uploading.
                    // domNodehandler(node, true);
                } else {
                    // latestPosition = TTXConstants.IN_TARGET_TUV;
                    domNodehandler(node, false);
                }
            } else {
                domNodehandler(node, false);
            }
        }
    } else {
        if (TTXConstants.UT.equalsIgnoreCase(elementName)) {
            Attribute displayTextAtt = element.attribute(TTXConstants.UT_ATT_DISPLAYTEXT);
            if (displayTextAtt != null) {
                String attValue = displayTextAtt.getValue();
                if (attValue != null && attValue.startsWith(TTXConstants.TU_ID)) {
                    // latestPosition = TTXConstants.TU_ID;
                    String tuId = attValue.substring(attValue.indexOf(":") + 1).trim();
                    if (results != null && results.length() > 0) {
                        results.append(TTXConstants.NEW_LINE).append(TTXConstants.NEW_LINE);
                    }
                    results.append(TTXConstants.HASH_MARK).append(tuId).append(TTXConstants.NEW_LINE);
                } else if (attValue != null && attValue.startsWith(TTXConstants.GS)) {
                    Attribute typeValueAtt = element.attribute(TTXConstants.UT_ATT_TYPE);
                    String typeValue = null;
                    if (typeValueAtt != null) {
                        typeValue = typeValueAtt.getValue();
                    }

                    String gsTag = attValue.substring(attValue.indexOf(":") + 1).trim();
                    if (typeValue != null && TTXConstants.UT_ATT_TYPE_START.equalsIgnoreCase(typeValue)) {
                        results.append("[").append(gsTag).append("]");
                    } else if (typeValue != null && TTXConstants.UT_ATT_TYPE_END.equalsIgnoreCase(typeValue)) {
                        results.append("[/").append(gsTag).append("]");
                    } else {
                        results.append("[").append(gsTag).append("]");
                        results.append("[/").append(gsTag).append("]");
                    }
                }
            }
        } else if (TTXConstants.DF.equalsIgnoreCase(elementName)) {
            // do not handle this.
        }
    }
}

From source file:com.globalsight.everest.tm.importer.ImportUtil.java

License:Apache License

/**
 * Returns the XML representation like Element.asXML() but without the
 * top-level tag.//  w  w  w . j  a va  2s.  com
 */
static public String getInnerXml(Element p_node) {
    StringBuffer result = new StringBuffer();

    List content = p_node.content();

    for (int i = 0, max = content.size(); i < max; i++) {
        Node node = (Node) content.get(i);

        // Work around a specific behaviour of DOM4J text nodes:
        // The text node asXML() returns the plain Unicode string,
        // so we need to encode entities manually.
        if (node.getNodeType() == Node.TEXT_NODE) {
            result.append(encodeXmlEntities(node.getText()));
        } else {
            // Element nodes write their text nodes correctly.
            result.append(node.asXML());
        }
    }

    return result.toString();
}

From source file:com.globalsight.terminology.EntryUtils.java

License:Apache License

/** Returns the list of <term> nodes in the entry. */
static public List getTerms(Node p_node) throws TermbaseException {
    Entry entry = new Entry(p_node.asXML());
    return getTerms(entry);
}

From source file:com.globalsight.terminology.EntryUtils.java

License:Apache License

/**
 * Returns the XML representation like Element.asXML() but without
 * the top-level tag.//from  ww  w  .  jav  a  2 s  . c om
 */
static public String getInnerXml(Element p_node) {
    StringBuffer result = new StringBuffer();

    List content = p_node.content();

    for (int i = 0, max = content.size(); i < max; i++) {
        Node node = (Node) content.get(i);

        // Work around a specific behaviour of DOM4J text nodes:
        // The text node asXML() returns the plain Unicode string,
        // so we need to encode entities manually.
        if (node.getNodeType() == Node.TEXT_NODE) {
            result.append(EditUtil.encodeXmlEntities(node.getText()));
        } else {
            // Element nodes write their text nodes correctly.
            result.append(node.asXML());
        }
    }

    return result.toString();
}