首页 > 解决方案 > 如何在 java 计算节点中遍历 XML 树

问题描述

我在使用 IIB v10 时遇到了一种情况,其中 SOAP Web 服务正在发送 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 计算节点中是否有任何方法允许遍历树中的每个元素并将其值作为字符串?

标签: javaibm-integration-busextended-sqlibm-app-connect

解决方案


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

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();
    }
}

推荐阅读