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

如何配置OMXMLBuilderFactory生成<a></a>而非<a/>形式的OMElement?

解决方案

解析得到的OMElement内部结构对于<a/>和<a></a>是完全一致的,两者的区别仅在于序列化输出时的格式控制,而非解析阶段的配置。你需要在输出OMElement时指定保留空元素的展开形式,而非调整解析器配置。

具体操作步骤:

  • 使用OMOutputFormat配置输出格式,开启setPreserveEmptyElements(true),该配置会强制空元素以<a></a>而非<a/>的形式输出。
  • 通过OMElement的serialize方法结合配置好的OMOutputFormat完成输出。

示例代码:

// 解析XML字符串得到OMElement
String inputXml = "<a></a>";
OMElement rootElement = OMXMLBuilderFactory.createOMBuilder(inputXml).getDocumentElement();

// 配置输出格式,保留空元素的展开形式
OMOutputFormat outputFormat = new OMOutputFormat();
outputFormat.setPreserveEmptyElements(true);

// 执行序列化输出
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
rootElement.serialize(outputStream, outputFormat);

// 输出结果为<a></a>
System.out.println(outputStream.toString());

补充说明:StAXParserConfiguration用于控制XML解析阶段的行为(如命名空间处理、实体解析等),并不负责输出格式的控制,因此你之前在解析配置里找不到对应项是正常的,空元素的展示格式属于序列化输出环节的配置范畴。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:29:53