我如何使用nokogiri xpath将元素添加到xml

问题描述 投票:0回答:1

我有以下xml

?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
   The .NET 2.0 build of the console runner only 
runs under .NET 2.0 or higher. The setting
useLegacyV2RuntimeActivationPolicy only applies 
under .NET 4.0 and permits use of mixed mode 
assemblies, which would otherwise not load 
correctly.
-->
<startup useLegacyV2RuntimeActivationPolicy="true">
    <!-- Comment out the next line to force use of .NET 4.0 -->
</startup>
<runtime>
    <!-- Ensure that test exceptions don't crash NUnit -->
    <legacyUnhandledExceptionPolicy enabled="1"/>
    <!-- Run partial trust V2 assemblies in full trust under .NET 4.0 -->
    <loadFromRemoteSources enabled="true"/>
    <!-- Look for addins in the addins directory for now -->
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <probing privatePath="lib;addins"/>
    </assemblyBinding>
</runtime>

使用rakefile.rb,我想在<startup>部分添加一个元素说:

<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />

因此它显示为:

<startup>
   <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>

到目前为止,在我的rakefile中,我有这个:

task :update_test_runner_supported_runtime do
    test_runner_path   = 'Packages\NUnit.Runners.2.6.4\tools\nunit-console-x86.exe.config'
    test_runner_config = Nokogiri::XML(open(functional_connection_path))
    functional_connection_config.xpath("//startup/")  #to find the start up element
    File.open(test_runner_path, 'w+') { |f| f.write(test_runner_config) } #to write the changes
end

我正在努力提出实际的语法,以为支持的运行时添加此详细信息。任何人都可以帮忙吗?

ruby xpath nokogiri rakefile
1个回答
0
投票

我想知道您是否可以通过简单的sub调用来实现?

test_runner_config.sub('<startup useLegacyV2RuntimeActivationPolicy="true">', '<startup>\n    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />')
File.open(test_runner_path, 'w+') { |f| f.write(test_runner_config) }
© www.soinside.com 2019 - 2024. All rights reserved.