如何防止REXML改变编码

时间:2011-06-01 02:23:12

标签: ruby xml rexml

我正在尝试使用Ruby和REXML编辑xml文件,但在将文件写回磁盘后,编码会发生变化。但我需要保留文件的原始编码!

这是我的xml在编辑之前的样子:

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'AdHoc|iPhone' ">
    <DebugType>none</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>..\Bin\iPhoneSimulator\AdHoc</OutputPath>
    <WarningLevel>4</WarningLevel>
    <MtouchUseSGen>false</MtouchUseSGen>
    <MtouchDebug>False</MtouchDebug>
    <CodesignKey>iPhone Developer:</CodesignKey>
    <MtouchUseLlvm>false</MtouchUseLlvm>
    <MtouchUseThumb>false</MtouchUseThumb>
    <MtouchArch>ARMv6</MtouchArch>
    <CodesignProvision>A2FBBCDB-218A-4CCC-88ED-A484AAE87EA5</CodesignProvision>
    <MtouchI18n />
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Xml" />
    <Reference Include="System.Core" />
    <Reference Include="monotouch" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Web.Services" />
    <Reference Include="System.Json" />
  </ItemGroup>

并在将其写回磁盘之后:

  <PropertyGroup Condition=' &apos;$(Configuration)|$(Platform)&apos; == &apos;AdHoc|iPhone&apos; '>
    <DebugType>none</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>..\Bin\iPhoneSimulator\AdHoc</OutputPath>
    <WarningLevel>4</WarningLevel>
    <MtouchUseSGen>false</MtouchUseSGen>
    <MtouchDebug>False</MtouchDebug>
    <CodesignKey>iPhone Developer:</CodesignKey>
    <MtouchUseLlvm>false</MtouchUseLlvm>
    <MtouchUseThumb>false</MtouchUseThumb>
    <MtouchArch>ARMv6</MtouchArch>
    <CodesignProvision>A2FBBCDB-218A-4CCC-88ED-A484AAE87EA5</CodesignProvision>
    <MtouchI18n/>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include='System'/>
    <Reference Include='System.Xml'/>
    <Reference Include='System.Core'/>
    <Reference Include='monotouch'/>
    <Reference Include='System.Xml.Linq'/>
    <Reference Include='System.Web.Services'/>
    <Reference Include='System.Json'/>
  </ItemGroup>

这是我的代码:

File.open('file.xml') do |config_file|
 # Open the document and edit the file
 config = Document.new(config_file)
 config.root.elements['PropertyGroup'].elements['CodesignKey'].text = 'my new developer'

 # Write the result to a new file.
 formatter = REXML::Formatters::Default.new
 File.open('file.xml', 'w') do |result|
  formatter.write(config, result)
 end
end

2 个答案:

答案 0 :(得分:1)

取自this post。初始化Document对象后设置属性定界符。

config = Document.new(config_file)
config.context[:attribute_quote] = :quote

答案 1 :(得分:0)

它与原始编码无关。您可以看到您的字符串被html转义字符替换。 替换为''替换为'

您可以尝试使用Nokogiri宝石

,而不是REXML

基本代码如下所示:

require 'rubygems'
require 'nokogiri'

filename = "file.xml"
doc = Nokogiri::XML(File.new(filename))

# Check the node content
doc.root.xpath("//MtouchArch").text

# do your processing
# ...

doc.to_xml