You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ballerina中相似XML值深度相等校验返回false的原因咨询

Ballerina XML深度相等校验返回false的原因及说明

在使用Ballerina处理XML值的深度相等校验时,遇到两个内容相似的XML字符串,通过xml1 == xml2比较却返回false,代码示例如下:

import ballerina/io;
xmlns "http://www.so2w.org" as s;

public function main() returns error? {
    string string1  = string 
    `<s:FuelEvents xmlns:s="http://www.so2w.org">

        <s:FuelEvent employeeId="2312">
            <s:odometerReading>230</s:odometerReading>
            <s:gallons>18.561</s:gallons>
            <s:gasPrice>4.56</s:gasPrice>
        </s:FuelEvent>
    </s:FuelEvents>`;

    string string2  = string 
    `<s:FuelEvents xmlns:s="http://www.so2w.org">
        <s:FuelEvent employeeId="2312">
            <s:odometerReading>230</s:odometerReading>
            <s:gallons>18.561</s:gallons>
            <s:gasPrice>4.56</s:gasPrice>
        </s:FuelEvent>
    </s:FuelEvents>`;

    xml xml1 = check xml:fromString(string1); 
    xml xml2 = check xml:fromString(string2);
    io:println(xml1 == xml2); // returns false
}

这属于预期行为,原因是Ballerina的XML解析会保留原始字符串中的空白节点(包括换行、空格、制表符等)。对比两个XML字符串的差异:

  • string1中<s:FuelEvents>标签后多了一个空行(包含额外的换行和空白字符)
  • string2中<s:FuelEvents>标签后直接跟随<s:FuelEvent>节点,无此空行

解析后的XML对象会将这些空白视为独立的文本节点,导致两个XML的结构存在差异,因此深度相等校验返回false。

若要忽略这类无关空白进行比较,可使用xml:canonicalize()方法对XML做规范化处理,移除不必要的空白节点后再比较,示例代码如下:

import ballerina/io;
xmlns "http://www.so2w.org" as s;

public function main() returns error? {
    // 省略xml1、xml2的解析代码
    
    string canonicalXml1 = check xml:canonicalize(xml1);
    string canonicalXml2 = check xml:canonicalize(xml2);
    io:println(canonicalXml1 == canonicalXml2); // 返回true
}

内容的提问来源于stack exchange,提问作者Nipuna Ranasinghe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:45:07