Java : Text (XML) with Examples

Text (Java SE 22 & JDK 22) with Examples.
You will find code examples on most Text methods.


Summary

The Text interface inherits from CharacterData and represents the textual content (termed character data in XML) of an Element or Attr.

Class diagram

Code examples on this page use the printDocument method below.

public void printDocument(Document document) throws TransformerException {
    final var transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    final var result = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(document), result);

    System.out.println(result.getWriter());
}
final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();

final var root = document.createElement("root");
System.out.println(root); // [root: null]

document.appendChild(root);

final var text = document.createTextNode("abcd");
System.out.println(text); // [#text: abcd]

root.appendChild(text);

//<root>abcd</root>
printDocument(document);

Fields declared in Node

ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_POSITION_CONTAINED_BY, DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, DOCUMENT_POSITION_PRECEDING, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE

Please see the link below.

Methods

String getWholeText ()

Returns all text of Text nodes logically-adjacent text nodes to this node, concatenated in document order.

final var xml = """
        <root/>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var root = document.getDocumentElement();
System.out.println(root);

final var aaa = document.createTextNode("aaa");
System.out.println(aaa); // [#text: aaa]

final var bbb = document.createTextNode("bbb");
System.out.println(bbb); // [#text: bbb]

root.appendChild(aaa);

//<root>aaa</root>
printDocument(document);

System.out.println(aaa.getWholeText()); // aaa
System.out.println(bbb.getWholeText()); // bbb

root.appendChild(bbb);

//<root>aaabbb</root>
printDocument(document);

System.out.println(aaa.getWholeText()); // aaabbb
System.out.println(bbb.getWholeText()); // aaabbb

boolean isElementContentWhitespace ()

Returns whether this text node contains element content whitespace, often abusively called "ignorable whitespace".

final var xml = """
        <!DOCTYPE root [
            <!ELEMENT child-a (dummy?)>
            <!ELEMENT child-b (#PCDATA)>
        ]>
        <root>
            <child-a> </child-a>
            <child-b> </child-b>
        </root>
        """;

final var factory = DocumentBuilderFactory.newInstance();

final var builder = factory.newDocumentBuilder();
builder.setErrorHandler(new DefaultHandler());

final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var childA = document.getElementsByTagName("child-a").item(0);
System.out.println(childA); // [child-a: null]

if (childA.getFirstChild() instanceof Text text) {
    System.out.println(text); // [#text:  ]
    System.out.println(text.isElementContentWhitespace()); // true
}

final var childB = document.getElementsByTagName("child-b").item(0);
System.out.println(childA); // [child-b: null]

if (childB.getFirstChild() instanceof Text text) {
    System.out.println(text); // [#text:  ]
    System.out.println(text.isElementContentWhitespace()); // false
}

Text replaceWholeText (String content)

Replaces the text of the current node and all logically-adjacent text nodes with the specified text.

final var xml = """
        <root>aaa</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var root = document.getDocumentElement();
System.out.println(root); // [root: null]

if (root.getFirstChild() instanceof Text text) {
    System.out.println(text); // [#text: aaa]

    //<root>aaa</root>
    printDocument(document);
    System.out.println(text.replaceWholeText("AAA")); // [#text: AAA]

    //<root>AAA</root>
    printDocument(document);

    root.appendChild(document.createTextNode("BBB"));

    //<root>AAABBB</root>
    printDocument(document);
    System.out.println(text.replaceWholeText("XXX")); // [#text: XXX]

    //<root>XXX</root>
    printDocument(document);
}

Text splitText (int offset)

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.

final var xml = """
        <root>abcde</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var root = document.getDocumentElement();
System.out.println(root); // [root: null]

if (root.getFirstChild() instanceof Text text) {
    System.out.println(text); // [#text: abcde]
    System.out.println(text.splitText(2)); // [#text: cde]
}

final var nodes = root.getChildNodes();
System.out.println("-- nodes --");
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i));
}

// Result
// ↓
//-- nodes --
//[#text: ab]
//[#text: cde]

Methods declared in CharacterData

appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData

Please see the link below.

Methods declared in Node

appendChild, cloneNode, compareDocumentPosition, getAttributes, getBaseURI, getChildNodes, getFeature, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, getTextContent, getUserData, hasAttributes, hasChildNodes, insertBefore, isDefaultNamespace, isEqualNode, isSameNode, isSupported, lookupNamespaceURI, lookupPrefix, normalize, removeChild, replaceChild, setNodeValue, setPrefix, setTextContent, setUserData

Please see the link below.


Related posts

To top of page