获取 child 之前的 parent 节点的字符串内容

Get string content of parent node that is before child

使用 Java,我试图弄清楚如何检索 parent 节点的字符串,直到 child 节点的开头:

<para>This is a paragraph with a child <dmRef><dmRefIdent><dmCode att="somevalue"/></dmRefIdent></dmRef> and then some more text.</para>

我想分析 .

开头之前的文本

我已经使用 node.getParent.getTextContent() 检索了完整的字符串,其中 node<dmRef> 元素,但我正在寻找一种方法来仅获取 [=15= 之前的文本]元素(这是一个带有child的段落)。

使用 XPath:

假定您在 para 元素节点的上下文中执行 XPath:

Select 第一个 dmRef 元素:

dmRef[1]

获取前面的兄弟文本节点:

dmRef[1]/preceding-sibling::text()

执行 XPath 将 return 一个节点列表。您将不得不迭代它并从每个节点获取文本内容。如果您确定这里只有一个文本节点,您可以将 ist 转换为 XPath 中的字符串:

string(dmRef[1]/preceding-sibling::text())