如何在java计算节点中遍历XML树

问题描述

我在使用 IIB v10 时遇到一种情况,即 SOAP 网络服务发送的 XML 响应在 相同 XML 元素中包含英语和REVERSED阿拉伯语。 >

示例:

<note>
  <to>Tove   رمع</to>
  <from>Jani  ريمس</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

应该是这个样子

<note>
  <to>Tove   عمر</to>
  <from>Jani  سمير</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

所以我已经准备了一些接受字符串的 Java 代码,将其拆分为字符串数组中的单词并检查单词是否为阿拉伯语单词,然后将其反转,然后重新连接字符串。

问题是后端响应有点大,我需要遍历 XML 树中的每个元素那么 Java 计算节点中是否有任何方法允许遍历树中的每个元素和以字符串形式获取它的值?

解决方法

递归是你的朋友。使用根元素调用以下函数:

import com.ibm.broker.plugin.MbElement;
import com.ibm.broker.plugin.MbException;
import com.ibm.broker.plugin.MbXMLNSC;

public void doYourThing(MbElement node) throws MbException {
    MbElement child = node.getFirstChild();
    while (child != null) {
        int specificType = child.getSpecificType();
        if (specificType == MbXMLNSC.FIELD) {
            String value = child.getValueAsString();
            // Do your thing
        }
        doYourThing(child);
        child = child.getNextSibling();
    }
}