gpt4 book ai didi

java - dom4j : adding PI in text content

转载 作者:行者123 更新时间:2023-12-01 10:43:57 26 4
gpt4 key购买 nike

我有以下元素:

<text>
text and text and text
<stop/>
text and text and text
<stop/>
text and text and text
<stop/>
</text>

我想在所有“和”文本之前和之后添加处理指令。像这样:

<text>
text<?Pub _newline>and<?Pub _newline>text<?Pub _newline>and<?Pub _newline>text
<stop/>
text<?Pub _newline>and<?Pub _newline>text<?Pub _newline>and<?Pub _newline>text
<stop/>
text<?Pub _newline>and<?Pub _newline>text<?Pub _newline>and<?Pub _newline>text
<stop/>
</text>

我不知道如何在文本中添加 PI 元素。如果我设置为字符串,它将被转义: >?Pub _newline<

最佳答案

示例文档中的 text 元素包含六个节点作为子节点:

  • 三个文本节点,每个节点包含文本text 和text 和text,以及
  • 三个元素(每个元素的名称为 stop)。

为了达到您想要的结果,我们需要将每个文本节点分解为文本节点和处理指令节点。

在 dom4j 中,我们可以使用 content 来做到这一点父元素的。此方法返回元素的所有子节点的列表,如果我们更改此列表,XML 文档也会更新。

因此,我们获取元素的内容列表,循环遍历所有子节点,当我们找到包含 的 Text 节点时,将该 Text 节点拆分为多个片段并将新片段插入到列表。

这里有一个方法演示了这种方法。向其传递一个元素,它将根据请求插入处理指令:

import org.dom4j.*;
import org.dom4j.tree.*;

// ...

public void insertProcessingInstructions(Element element) {
List nodes = element.content();
final String splitter = " and ";
int index = 0;
while (index < nodes.size()) {
if (nodes.get(index) instanceof Text) {
Text textNode = (Text)nodes.get(index);
String text = textNode.getText();
int andPos = text.indexOf(splitter);
if (andPos >= 0) {
String beforeText = text.substring(0, andPos);
String afterText = text.substring(andPos + splitter.length());
textNode.setText(beforeText);
nodes.add(index + 1, new DefaultProcessingInstruction("Pub", "_newline"));
nodes.add(index + 2, new DefaultText(splitter.trim()));
nodes.add(index + 3, new DefaultProcessingInstruction("Pub", "_newline"));
nodes.add(index + 4, new DefaultText(afterText));
// Move to the last Text node created, in case it contains another
// occurrence of the splitter string.
index += 4;
} else {
// No more occurrences of the splitter string in this Text node.
++index;
}
} else {
// Not a Text node.
++index;
}
}
}

关于java - dom4j : adding PI in text content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34306738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com