org.jdom.Text Java Examples

The following examples show how to use org.jdom.Text. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UpgradeXGAPP.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * If this element has any child <em>elements</em>, add whitespace
 * text nodes inside this element to indent its children to the
 * appropriate level, and then do the same recursively for the children.
 * This doesn't work for elements with mixed content - content must be
 * either other elements or text, not both.
 * @param e the element to pretty print
 * @param numAncestors the number of ancestor elements this element
 *                     will have once it is inserted into the tree
 *                     (i.e. the "depth" of this element).
 */
@SuppressWarnings("unchecked")
private static void prettyPrint(Element e, int numAncestors) {
  if(!e.getChildren().isEmpty()) {
    int numChildren = e.getContentSize();
    // add indent before the closing tag
    e.addContent(numChildren, new Text("\n" + StringUtils.repeat(" ", 2*numAncestors)));
    // add a bit more indent before each child - we have to work backwards
    // as the act of adding text nodes changes the content indexes for
    // subsequent children
    String indentStr = "\n" + StringUtils.repeat(" ", 2*(numAncestors+1));
    for(int i = numChildren - 1; i >= 0; i--) {
      e.addContent(i, new Text(indentStr));
    }

    // now recursively prettify the children
    for(Element child : (List<Element>)e.getChildren()) {
      prettyPrint(child, numAncestors + 1);
    }
  }
}
 
Example #2
Source File: AbstractCollectionBinding.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private Object serializeItem(@Nullable Object value, Object context, @Nonnull SerializationFilter filter) {
  if (value == null) {
    LOG.warn("Collection " + myAccessor + " contains 'null' object");
    return null;
  }

  Binding binding = XmlSerializerImpl.getBinding(value.getClass());
  if (binding == null) {
    Element serializedItem = new Element(annotation == null ? Constants.OPTION : annotation.elementTag());
    String attributeName = annotation == null ? Constants.VALUE : annotation.elementValueAttribute();
    String serialized = XmlSerializerImpl.convertToString(value);
    if (attributeName.isEmpty()) {
      if (!serialized.isEmpty()) {
        serializedItem.addContent(new Text(serialized));
      }
    }
    else {
      serializedItem.setAttribute(attributeName, serialized);
    }
    return serializedItem;
  }
  else {
    return binding.serialize(value, context, filter);
  }
}
 
Example #3
Source File: JDOMStreamReader.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected int nextChild() {
    int currentChild = getCurrentFrame().getCurrentChild();
    currentChild++;
    getCurrentFrame().setCurrentChild(currentChild);
    this.content = getCurrentElement().getContent(currentChild);

    if (content instanceof Text) {
        return CHARACTERS;
    } else if (content instanceof Element) {
        setupNamespaces((Element)content);
        return START_ELEMENT;
    } else if (content instanceof Comment) {
        return CHARACTERS;
    } else if (content instanceof EntityRef) {
        return ENTITY_REFERENCE;
    }

    throw new IllegalStateException();
}
 
Example #4
Source File: TagBinding.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public Object serialize(@Nonnull Object o, @Nullable Object context, @Nonnull SerializationFilter filter) {
  Object value = myAccessor.read(o);
  Element serialized = new Element(myName);
  if (value == null) {
    return serialized;
  }

  if (myBinding == null) {
    serialized.addContent(new Text(XmlSerializerImpl.convertToString(value)));
  }
  else {
    Object node = myBinding.serialize(value, serialized, filter);
    if (node != null && node != serialized) {
      JDOMUtil.addContent(serialized, node);
    }
  }
  return serialized;
}
 
Example #5
Source File: JDOMNodePointer.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
/**
 * Get the parent of the specified node.
 * @param node to check
 * @return parent Element
 */
private static Element nodeParent(Object node) {
    if (node instanceof Element) {
        Object parent = ((Element) node).getParent();
        return parent instanceof Element ? (Element) parent : null;
    }
    if (node instanceof Text) {
        return (Element) ((Text) node).getParent();
    }
    if (node instanceof CDATA) {
        return (Element) ((CDATA) node).getParent();
    }
    if (node instanceof ProcessingInstruction) {
        return (Element) ((ProcessingInstruction) node).getParent();
    }
    if (node instanceof Comment) {
        return (Element) ((Comment) node).getParent();
    }
    return null;
}
 
Example #6
Source File: PathMacrosCollectorTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testCollectMacros() {
  Element root = new Element("root");
  root.addContent(new Text("$MACro1$ some text $macro2$ other text $MACRo3$"));
  root.addContent(new Text("$macro4$ some text"));
  root.addContent(new Text("some text$macro5$"));
  root.addContent(new Text("file:$mac_ro6$"));
  root.addContent(new Text("jar://$macr.o7$ "));
  root.addContent(new Text("$mac-ro8$ "));
  root.addContent(new Text("$$$ "));
  root.addContent(new Text("$c:\\a\\b\\c$ "));
  root.addContent(new Text("$Revision 1.23$"));

  final Set<String> macros = PathMacrosService.getInstance().getMacroNames(root, null, new PathMacrosImpl());

  assertEquals(5, macros.size());
  assertTrue(macros.contains("MACro1"));
  assertTrue(macros.contains("macro4"));
  assertTrue(macros.contains("mac_ro6"));
  assertTrue(macros.contains("macr.o7"));
  assertTrue(macros.contains("mac-ro8"));
}
 
Example #7
Source File: CompositePathMacroFilter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean recursePathMacros(Text element) {
  for (PathMacroFilter filter : myFilters) {
    if (filter.recursePathMacros(element)) return true;
  }
  return false;
}
 
Example #8
Source File: XmlSerializerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
static String getTextValue(@Nonnull Element element, @Nonnull String defaultText) {
  List<Content> content = element.getContent();
  String value = defaultText;
  if (!content.isEmpty()) {
    Content child = content.get(0);
    if (child instanceof Text) {
      value = child.getValue();
    }
  }
  return value;
}
 
Example #9
Source File: JDOMNodePointer.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
/**
 * Add the specified content to this element.
 * @param content List
 */
private void addContent(List content) {
    Element element = (Element) node;
    int count = content.size();

    for (int i = 0; i < count; i++) {
        Object child = content.get(i);
        if (child instanceof Element) {
            child = ((Element) child).clone();
            element.addContent((Element) child);
        }
        else if (child instanceof Text) {
            child = ((Text) child).clone();
            element.addContent((Text) child);
        }
        else if (node instanceof CDATA) {
            child = ((CDATA) child).clone();
            element.addContent((CDATA) child);
        }
        else if (node instanceof ProcessingInstruction) {
            child = ((ProcessingInstruction) child).clone();
            element.addContent((ProcessingInstruction) child);
        }
        else if (node instanceof Comment) {
            child = ((Comment) child).clone();
            element.addContent((Comment) child);
        }
    }
}
 
Example #10
Source File: CustomWalker.java    From consulo with Apache License 2.0 5 votes vote down vote up
private final boolean isTextLike(final Content c) {
  switch (c.getCType()) {
    case Text:
    case CDATA:
    case EntityRef:
      return true;
    default:
      // nothing.
  }
  return false;
}
 
Example #11
Source File: CompositePathMacroFilter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean skipPathMacros(Text element) {
  for (PathMacroFilter filter : myFilters) {
    if (filter.skipPathMacros(element)) return true;
  }
  return false;
}
 
Example #12
Source File: Utils.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
/**
 * Method updateElement.
 * 
 * @param counter
 * @param shouldExist
 * @param name
 * @param parent
 * @return Element
 */
public static Element updateElement( final IndentationCounter counter, final Element parent, final String name,
                                     final boolean shouldExist )
{
    Element element = parent.getChild( name, parent.getNamespace() );
    if ( shouldExist )
    {
        if ( element == null )
        {
            element = factory.element( name, parent.getNamespace() );
            insertAtPreferredLocation( parent, element, counter );
        }
        counter.increaseCount();
    }
    else if ( element != null )
    {
        final int index = parent.indexOf( element );
        if ( index > 0 )
        {
            final Content previous = parent.getContent( index - 1 );
            if ( previous instanceof Text )
            {
                final Text txt = (Text) previous;
                if ( txt.getTextTrim().length() == 0 )
                {
                    parent.removeContent( txt );
                }
            }
        }
        parent.removeContent( element );
    }
    return element;
}
 
Example #13
Source File: XmlToPlainText.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private void process(Text current) {
    String text = current.getTextTrim();
    if (!StringUtils.isBlank(text)) {
        if (plainText.length() > 0 && IGNORABLES.indexOf(text) < 0) {
            plainText.append(" ");
        }
        plainText.append(text);
        if (!StringUtils.isBlank(href)) {
            plainText.append(" (").append(href).append(")");
            href = null;
        }
    }
}
 
Example #14
Source File: XmlToPlainText.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
private void process(Text current) {
    String text = current.getTextTrim();
    if (!StringUtils.isBlank(text)) {
        if (plainText.length() > 0 && IGNORABLES.indexOf(text) < 0) {
            plainText.append(" ");
        }
        plainText.append(text);
        if (!StringUtils.isBlank(href)) {
            plainText.append(" (").append(href).append(")");
            href = null;
        }
    }
}
 
Example #15
Source File: NetbeansBuildActionJDOMWriter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Method updateElement.
 * 
 * @param counter
 * @param shouldExist
 * @param name
 * @param parent
 * @return Element
 */
protected Element updateElement(Counter counter, Element parent, String name, boolean shouldExist)
{
    Element element =  parent.getChild(name, parent.getNamespace());
    if (element != null && shouldExist) {
        counter.increaseCount();
    }
    if (element == null && shouldExist) {
        element = factory.element(name, parent.getNamespace());
        insertAtPreferredLocation(parent, element, counter);
        counter.increaseCount();
    }
    if (!shouldExist && element != null) {
        int index = parent.indexOf(element);
        if (index > 0) {
            Content previous = parent.getContent(index - 1);
            if (previous instanceof Text) {
                Text txt = (Text)previous;
                if (txt.getTextTrim().length() == 0) {
                    parent.removeContent(txt);
                }
            }
        }
        parent.removeContent(element);
    }
    return element;
}
 
Example #16
Source File: JDOMModelTest.java    From commons-jxpath with Apache License 2.0 4 votes vote down vote up
private void appendXMLSignature(
    StringBuffer buffer,
    Object object,
    boolean elements,
    boolean attributes,
    boolean text,
    boolean pi) 
{
    if (object instanceof Document) {
        buffer.append("<D>");
        appendXMLSignature(
            buffer,
            ((Document) object).getContent(),
            elements,
            attributes,
            text,
            pi);
        buffer.append("</D");
    }
    else if (object instanceof Element) {
        String tag = elements ? ((Element) object).getName() : "E";
        buffer.append("<");
        buffer.append(tag);
        buffer.append(">");
        appendXMLSignature(
            buffer,
            ((Element) object).getContent(),
            elements,
            attributes,
            text,
            pi);
        buffer.append("</");
        buffer.append(tag);
        buffer.append(">");
    }
    else if (object instanceof Text || object instanceof CDATA) {
        if (text) {
            String string = ((Text) object).getText();
            string = string.replace('\n', '=');
            buffer.append(string);
        }
    }
}
 
Example #17
Source File: JDOMNodePointer.java    From commons-jxpath with Apache License 2.0 4 votes vote down vote up
/**
 * Execute test against node on behalf of pointer.
 * @param pointer Pointer
 * @param node to test
 * @param test to execute
 * @return true if node passes test
 */
public static boolean testNode(
    NodePointer pointer,
    Object node,
    NodeTest test) {
    if (test == null) {
        return true;
    }
    if (test instanceof NodeNameTest) {
        if (!(node instanceof Element)) {
            return false;
        }

        NodeNameTest nodeNameTest = (NodeNameTest) test;
        QName testName = nodeNameTest.getNodeName();
        String namespaceURI = nodeNameTest.getNamespaceURI();
        boolean wildcard = nodeNameTest.isWildcard();
        String testPrefix = testName.getPrefix();
        if (wildcard && testPrefix == null) {
            return true;
        }
        if (wildcard
            || testName.getName()
                    .equals(JDOMNodePointer.getLocalName(node))) {
            String nodeNS = JDOMNodePointer.getNamespaceURI(node);
            return equalStrings(namespaceURI, nodeNS) || nodeNS == null
                    && equalStrings(testPrefix, getPrefix(node));
        }
        return false;
    }
    if (test instanceof NodeTypeTest) {
        switch (((NodeTypeTest) test).getNodeType()) {
            case Compiler.NODE_TYPE_NODE :
                return true;
            case Compiler.NODE_TYPE_TEXT :
                return (node instanceof Text) || (node instanceof CDATA);
            case Compiler.NODE_TYPE_COMMENT :
                return node instanceof Comment;
            case Compiler.NODE_TYPE_PI :
                return node instanceof ProcessingInstruction;
            default:
                return false;
        }
    }
    if (test instanceof ProcessingInstructionTest && node instanceof ProcessingInstruction) {
        String testPI = ((ProcessingInstructionTest) test).getTarget();
        String nodePI = ((ProcessingInstruction) node).getTarget();
        return testPI.equals(nodePI);
    }
    return false;
}
 
Example #18
Source File: JDOMNodePointer.java    From commons-jxpath with Apache License 2.0 4 votes vote down vote up
public String asPath() {
    if (id != null) {
        return "id('" + escape(id) + "')";
    }

    StringBuffer buffer = new StringBuffer();
    if (parent != null) {
        buffer.append(parent.asPath());
    }
    if (node instanceof Element) {
        // If the parent pointer is not a JDOMNodePointer, it is
        // the parent's responsibility to produce the node test part
        // of the path
        if (parent instanceof JDOMNodePointer) {
            if (buffer.length() == 0
                || buffer.charAt(buffer.length() - 1) != '/') {
                buffer.append('/');
            }
            String nsURI = getNamespaceURI();
            String ln = JDOMNodePointer.getLocalName(node);

            if (nsURI == null) {
                buffer.append(ln);
                buffer.append('[');
                buffer.append(getRelativePositionByQName()).append(']');
            }
            else {
                String prefix = getNamespaceResolver().getPrefix(nsURI);
                if (prefix != null) {
                    buffer.append(prefix);
                    buffer.append(':');
                    buffer.append(ln);
                    buffer.append('[');
                    buffer.append(getRelativePositionByQName());
                    buffer.append(']');
                }
                else {
                    buffer.append("node()");
                    buffer.append('[');
                    buffer.append(getRelativePositionOfElement());
                    buffer.append(']');
                }
            }

        }
    }
    else if (node instanceof Text || node instanceof CDATA) {
        buffer.append("/text()");
        buffer.append('[').append(getRelativePositionOfTextNode()).append(
            ']');
    }
    else if (node instanceof ProcessingInstruction) {
        buffer.append("/processing-instruction(\'").append(((ProcessingInstruction) node).getTarget()).append(
            "')");
        buffer.append('[').append(getRelativePositionOfPI()).append(
            ']');
    }
    return buffer.toString();
}
 
Example #19
Source File: TextBinding.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public Object serialize(@Nonnull Object o, @Nullable Object context, @Nonnull SerializationFilter filter) {
  Object value = myAccessor.read(o);
  return value == null ? null : new Text(XmlSerializerImpl.convertToString(value));
}
 
Example #20
Source File: ImmutableText.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected Text setParent(Parent parent) {
  throw ImmutableElement.immutableError(this);
  //return null; // to be able to add this to the other element
}
 
Example #21
Source File: ImmutableText.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Text detach() {
  throw ImmutableElement.immutableError(this);
}
 
Example #22
Source File: ImmutableText.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void append(Text text) {
  throw ImmutableElement.immutableError(this);
}
 
Example #23
Source File: ImmutableText.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Text setText(String str) {
  throw ImmutableElement.immutableError(this);
}
 
Example #24
Source File: ImmutableText.java    From consulo with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("MethodDoesntCallSuperMethod")
@Override
public Text clone() {
  return new Text(value);
}
 
Example #25
Source File: PathMacroFilter.java    From consulo with Apache License 2.0 4 votes vote down vote up
public boolean recursePathMacros(Text element) {
  return false;
}
 
Example #26
Source File: PathMacroFilter.java    From consulo with Apache License 2.0 4 votes vote down vote up
public boolean skipPathMacros(Text element) {
  return false;
}
 
Example #27
Source File: StaxSerializer.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void writeElement(Element e, XMLStreamWriter writer) throws XMLStreamException {
    // need to check if the namespace is declared before we write the
    // start element because that will put the namespace in the context.
    String elPrefix = e.getNamespacePrefix();
    String elUri = e.getNamespaceURI();

    String boundPrefix = writer.getPrefix(elUri);
    boolean writeElementNS = false;
    if (boundPrefix == null || !elPrefix.equals(boundPrefix)) {
        writeElementNS = true;
    }

    writer.writeStartElement(elPrefix, e.getName(), elUri);

    List<?> namespaces = e.getAdditionalNamespaces();
    for (Iterator<?> itr = namespaces.iterator(); itr.hasNext();) {
        Namespace ns = (Namespace)itr.next();

        String prefix = ns.getPrefix();
        String uri = ns.getURI();

        writer.setPrefix(prefix, uri);
        writer.writeNamespace(prefix, uri);

        if (elUri.equals(uri) && elPrefix.equals(prefix)) {
            writeElementNS = false;
        }
    }

    for (Iterator<?> itr = e.getAttributes().iterator(); itr.hasNext();) {
        Attribute attr = (Attribute)itr.next();
        String attPrefix = attr.getNamespacePrefix();
        String attUri = attr.getNamespaceURI();

        if (attUri == null || attUri.isEmpty()) {
            writer.writeAttribute(attr.getName(), attr.getValue());
        } else {
            writer.writeAttribute(attPrefix, attUri, attr.getName(), attr.getValue());

            if (!isDeclared(writer, attPrefix, attUri)) {
                if (elUri.equals(attUri) && elPrefix.equals(attPrefix)) {
                    if (writeElementNS) {
                        writer.setPrefix(attPrefix, attUri);
                        writer.writeNamespace(attPrefix, attUri);
                        writeElementNS = false;
                    }
                } else {
                    writer.setPrefix(attPrefix, attUri);
                    writer.writeNamespace(attPrefix, attUri);
                }
            }
        }
    }

    if (writeElementNS) {
        if (elPrefix == null || elPrefix.length() == 0) {
            writer.writeDefaultNamespace(elUri);
        } else {
            writer.writeNamespace(elPrefix, elUri);
        }
    }

    for (Iterator<?> itr = e.getContent().iterator(); itr.hasNext();) {
        Content n = (Content)itr.next();
        if (n instanceof CDATA) {
            writer.writeCData(n.getValue());
        } else if (n instanceof Text) {
            writer.writeCharacters(((Text)n).getText());
        } else if (n instanceof Element) {
            writeElement((Element)n, writer);
        } else if (n instanceof Comment) {
            writer.writeComment(n.getValue());
        } else if (n instanceof EntityRef) {
            // EntityRef ref = (EntityRef) n;
            // writer.writeEntityRef(ref.)
        }
    }

    writer.writeEndElement();
}
 
Example #28
Source File: JDOMStreamReader.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public String getElementText() throws XMLStreamException {
    return ((Text)content).getText();
}