添加前缀到 XML 根节点

Add prefix to XML root node

我正在使用 Nokogiri 生成 XML。我只想将命名空间前缀添加到 XML 根节点,但问题是将前缀应用于第一个元素,它适用于所有子元素。

这是我的预期结果:

<?xml version="1.0" encoding="UTF-8"?>
<req:Request xmlns:req="http://www.google.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" schemaVersion="1.0">
 <LanguageCode>en</LanguageCode>
 <Enabled>Y</Enabled>
</req:Request>

尝试添加属性 xmlns="",这似乎向 XML 构建器暗示元素应该位于默认名称空间中,除非另有声明。我 相信 生成的文档在语义上等同于您的示例,尽管它存在...

attrs = {
  'xmlns' => '',
  'xmlns:req' => 'http://www.google.com',
  'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
  'schemaVersion' => '1.0',
}
builder = Nokogiri::XML::Builder.new do |xml|
  xml['req'].Request(attrs) {
    xml.LanguageCode('en')
    xml.Enabled('Y')
  }
end

builder.to_xml # =>
# <?xml version="1.0"?>
# <req:Request xmlns="" xmlns:req="http://www.google.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" schemaVersion="1.0">
#   <LanguageCode>en</LanguageCode>
#   <Enabled>Y</Enabled>
# </req:Request>