如何使用Nokogiri生成带连字符分隔的命名空间XML标签?
解决Nokogiri生成带命名空间且连字符分隔标签的XML问题
没问题,我来帮你调整代码,实现你想要的XML输出效果。你遇到的核心问题是Ruby方法名不支持连字符,所以不能直接像x['ns3'].exemplo-teste这样写,得用send方法来调用带特殊字符的标签名,同时确保命名空间正确绑定。
修改后的代码如下:
require 'nokogiri' teste = Nokogiri::XML::DocumentFragment.parse("") Nokogiri::XML::Builder.with(teste) do |x| x.root('xmlns:ns3' => 'Example namespace') do # 用send方法调用带连字符的标签名,同时指定命名空间前缀 x['ns3'].send('exemplo-teste', 'teste') end end puts teste.to_xml
运行这段代码后,输出就会和你期望的一致:
<root xmlns:ns3="Example namespace"> <ns3:exemplo-teste>teste</ns3:exemplo-teste> </root>
关键说明:
- Ruby的方法名称不允许包含连字符,所以我们用
send方法动态调用对应的标签名,把'exemplo-teste'作为字符串参数传给send,就能生成带连字符的标签。 x['ns3']确保标签使用指定的命名空间前缀,和root节点里定义的xmlns:ns3对应上。- 如果只需要输出单个
<ns3:exemplo-teste>标签(不需要外层root),可以去掉root节点的代码,直接在builder里生成目标标签:
require 'nokogiri' teste = Nokogiri::XML::DocumentFragment.parse("") Nokogiri::XML::Builder.with(teste) do |x| x.parent.namespace = x.parent.add_namespace('ns3', 'Example namespace') x.send('exemplo-teste', 'teste') end puts teste.to_xml
这段代码的输出就是:
<ns3:exemplo-teste xmlns:ns3="Example namespace">teste</ns3:exemplo-teste>
内容的提问来源于stack exchange,提问作者Ailton
相关产品推荐
相关产品推荐

