在添加节点时,让Nokogiri不添加"默认"命名空间

Nic*_*eri 1 ruby xml nokogiri

背景:

我想从一个文件中获取一些xml,将其放在模板文件中,然后将修改后的模板保存为新文件.它可以正常工作,但是当我保存文件时,我添加的所有节点都有一个预先定义的默认命名空间,即

        <default:ComponentRef Id="C__AD1817F9C64A42F0A14DDDDC82DFC8D9"/>
        <default:ComponentRef Id="C__157DD41D70854617A3D6D1E4A39B589F"/>
        <default:ComponentRef Id="C__2E6D8662F38FE62CAFA9F8842A28F510"/>
        <default:ComponentRef Id="C__54E5E2181323D4A5F37293DAA87B4230"/>
Run Code Online (Sandbox Code Playgroud)

我想要的只是:

        <ComponentRef Id="C__AD1817F9C64A42F0A14DDDDC82DFC8D9"/>
        <ComponentRef Id="C__157DD41D70854617A3D6D1E4A39B589F"/>
        <ComponentRef Id="C__2E6D8662F38FE62CAFA9F8842A28F510"/>
        <ComponentRef Id="C__54E5E2181323D4A5F37293DAA87B4230"/>
Run Code Online (Sandbox Code Playgroud)

以下是我的ruby代码:

file = "wixmain/generated/DarkOutput.wxs"
template = "wixmain/generated/MsiComponentTemplate.wxs"
output = "wixmain/generated/MSIComponents.wxs"

dark_output = Nokogiri::XML(File.open(file))
template_file = Nokogiri::XML(File.open(template))

#get stuff from dark output
components = dark_output.at_css("Directory[Id='TARGETDIR']")
component_ref = dark_output.at_css("Feature[Id='DefaultFeature']")

#where to insert in template doc
template_component_insert_point = template_file.at_css("DirectoryRef[Id='InstallDir']")
template_ref_insert_point = template_file.at_css("ComponentGroup[Id='MSIComponentGroup']")

template_component_insert_point.children= components.children()
template_ref_insert_point.children= component_ref.children()

#write out filled template to output file
File.open(output, 'w') { |f| template_file.write_xml_to f }
Run Code Online (Sandbox Code Playgroud)

更新

我的模板文件示例:

<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
  <Fragment>
    <ComponentGroup Id='MSIComponentGroup'>
    </ComponentGroup>
  </Fragment>
  <Fragment Id='MSIComponents'>
      <DirectoryRef Id='InstallDir'>
      </DirectoryRef>
  </Fragment>
</Wix>
Run Code Online (Sandbox Code Playgroud)

Nic*_*eri 6

解决方法是删除输入文件中的xmlns属性.

或者使用remove_namespaces!打开输入文件时的方法

input_file = Nokogiri::XML(File.open(input))
input_file.remove_namespaces!
Run Code Online (Sandbox Code Playgroud)