Skip to content

Commit

Permalink
Implement DOMNode.getTextContent() according to API
Browse files Browse the repository at this point in the history
Fix eclipse-lemminx#1695

Signed-off-by: Christoph Läubrich <laeubi@laeubi-soft.de>
  • Loading branch information
laeubi committed Nov 10, 2024
1 parent 0aadd16 commit c7080b1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -827,7 +827,39 @@ public DOMElement getOrphanEndElement(int offset, String tagName, boolean anyOrp
*/
@Override
public String getTextContent() throws DOMException {
return getNodeValue();

switch (getNodeType()) {
// Text like nodes simply return their node value
case Node.TEXT_NODE:
case Node.CDATA_SECTION_NODE:
case Node.COMMENT_NODE:
case Node.PROCESSING_INSTRUCTION_NODE:
return getNodeValue();
// These special types has to return null
case Node.DOCUMENT_NODE:
case Node.DOCUMENT_TYPE_NODE:
case Node.NOTATION_NODE:
return null;
// concatenation of the textContent attribute value of every child node
default:
if (this.children != null && children.size() > 0) {
final StringBuilder builder = new StringBuilder();
for (DOMNode child : children) {
short nodeType = child.getNodeType();
if (nodeType == Node.COMMENT_NODE || nodeType == Node.PROCESSING_INSTRUCTION_NODE) {
// excluding COMMENT_NODE and PROCESSING_INSTRUCTION_NODE nodes.
continue;
}
String text = child.getTextContent();
if (text != null && !text.isEmpty()) {
builder.append(text);
}
}
return builder.toString();
}
// empty string if the node has no children
return "";
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ public void testNestedElement() {
assertDocument("<html><body></body></html>", html);
}

@Test
public void testGetText() {
DOMDocument document = DOMParser.getInstance().parse("<a><b><c>Hello</c></b></a>", "uri", null);
String textContent = document.getDocumentElement().getTextContent();
assertNotNull(textContent);
assertEquals("Hello", textContent);
}

@Test
public void testNestedElements() {
DOMNode head = createElement("head", 6, 12, 19, true);
Expand Down

0 comments on commit c7080b1

Please sign in to comment.