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

Ruby中如何从XML格式字符串提取属性值与标签内容

方案1:使用Ruby内置REXML模块(推荐)

XML结构的解析优先使用专门的XML解析工具,比正则兼容性、稳定性更高,Ruby内置了REXML模块无需额外安装依赖:

require "rexml/document"

input_str = '<string name="animal">dog</string>'
doc = REXML::Document.new(input_str)
string_node = doc.root

# 提取name属性值
name_value = string_node.attributes["name"]
# 输出 => "animal"

# 提取标签包裹的文本内容
content_value = string_node.text
# 输出 => "dog"
方案2:正则实现(仅适用于固定简单格式场景)

如果你的输入字符串格式完全固定,没有特殊转义字符、额外属性,可以用正则快速提取:

input_str = '<string name="animal">dog</string>'

# 单独提取name属性
name_value = input_str.match(/name="([^"]+)"/)[1]
# 输出 => "animal"

# 单独提取标签内容
content_value = input_str.match(/>([^<]+)<\/string>/)[1]
# 输出 => "dog"

注意:正则方案无法处理属性值含转义双引号、文本内容含<符号、标签存在其他属性等复杂情况,生产环境优先使用XML解析方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:42:02