Java : Text (XML) 示例

Text (Java SE 22 & JDK 22) 示例。
您将在大多数 Text 方法中找到代码示例。

注解 :

  • 本文可能使用了翻译软件以方便阅读。 另请查看英文原文

简介

Text 接口继承自 CharacterData,表示 Element 或 Attr 的文本内容(在 XML 中称为字符数据)。 (机器翻译)

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

请参阅下面的链接。

Methods

String getWholeText ()

返回与该节点逻辑相邻的文本节点的所有文本,按文档顺序连接。 (机器翻译)

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 ()

返回此文本节点是否包含元素内容空格,通常被滥用为“可忽略空格”。 (机器翻译)

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)

用指定的文本替换当前节点和所有逻辑相邻的文本节点的文本。 (机器翻译)

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)

按照指定的偏移量将此节点拆分为两个节点,并将两个节点保留在树中作为兄弟节点。 (机器翻译)

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

请参阅下面的链接。

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

请参阅下面的链接。


相关文章

To top of page