Вопрос

I am trying to read the content of an XML file (configs.xml) and insert it somewhere in the middle of another XML file (workspace.xml).

This is the code:

require "nokogiri" 

workspace = File.open("workspace.xml")
xml = Nokogiri::XML(workspace)
workspace.close

# Add new configs
configs = File.read("configs.xml")
xml.search('component[name="RunManager"]').each do |node|
    node.content=configs
end

puts xml

The output looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="AndroidLayoutPreviewToolWindow">
    <option name="state">
      <GlobalState/>
    </option>
  </component>
  <component name="RunManager" selected="Android Application.Run on device">    
    &lt;configuration default="true" type="AndroidTestRunConfigurationType" factoryName="Android Tests"&gt;
      &lt;module name="" /&gt;
      &lt;option name="TESTING_TYPE" value="0" /&gt;
      &lt;option name="INSTRUMENTATION_RUNNER_CLASS" value="" /&gt;
      &lt;option name="METHOD_NAME" value="" /&gt;
      &lt;option name="CLASS_NAME" value="" /&gt;         
    &lt;/configuration&gt;
</component>
  <component name="ShelveChangesManager" show_recycled="false"/>
  <component name="SliceManager" selected="Android Application.Run on device">
    <option name="analysisUIOptions">
      <AnalysisUIOptions/>
    </option>
  </component>
</project>

As you can see, the inserted content in the middle has all angular braces < > replaced with HTML codes &lt; &gt, and I don't know why, though I suspect this has to do something with encodings.

What is most interesting is that if printing the content of configs.xml alone (the one that gets inserted and modified) then the output is as expected:

<configuration default="true" type="AndroidTestRunConfigurationType" factoryName="Android Tests">
      <option name="TESTING_TYPE" value="0" />
      <option name="INSTRUMENTATION_RUNNER_CLASS" value="" />
      <option name="METHOD_NAME" value="" />
      // ............
</configuration>
Это было полезно?

Решение

When you set the contents of a node you actually set its text contents, meaning, Nokogiri automatically escapes it.

To add a node to your XML you need to use add_child

configs = File.read("configs.xml")
xml.search('component[name="RunManager"]').each do |node|
    node.add_child configs
end
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top