Dom4J:如何用文本值

时间:2018-03-07 03:25:13

标签: java dom4j

我正在使用dom4j像这样解析xml:

<node>
    somestring<br/>some <a href="stackoverflow.com">another string</a> 
</node>

我想将此更改为另一个xml,如下所示:

<node>
    somestring<br/>some another string
</node>

dom4j有可能吗?

我认为诀窍是解析文本中的节点。

1 个答案:

答案 0 :(得分:0)

您可以通过运行节点元素内容并替换&#34; a&#34;来实现您想要做的事情。标记其文本值。

假设您将节点放入Element对象

String originalXml = "<node>somestring<br/>some <a href=\"stackoverflow.com\">another string</a></node>";
Document document = DocumentHelper.parseText(originalXml);
Element nodeElement = document.getRootElement();

您可以这样做,请参阅内联评论:

// once you have your node, as an Element object, get its content
List<Object> content = nodeElement.content();

// go through the content list and replace any "a" tag by its text value
List<Object> newContent = new ArrayList<>();
for(Object o : content) {
  Object newContentObject = o; // keep the same value by default
  if(o instanceof DefaultElement) {
    DefaultElement elem = (DefaultElement)o;
    String tagName = elem.getQName().getName();
    if("a".equals(tagName)) // this is an "a" tag, replace it by a text element
      newContentObject = new DefaultText(elem.getText());
  }
  newContent.add(newContentObject);
}

// Set the new content to your element
nodeElement.setContent(newContent);

System.out.print(nodeElement.asXML());

输出:

<node>somestring<br/>some another string</node>