2016-03-18 174 views
0

我有一個XML文件。 例子:覆蓋XML標記內容

<string name="example1">example1</string> 
<string name="example2">example2</string> 
<string name="example3" warning="true">example3</string> 
<string name="example4">example4</string> 
<string name="example5"warning="true">example5</string> 
<string name="example6">example6</string> 

我想創建一個腳本,包括<WARNING[[" "]]>如果warning="true"

目的是有:

<string name="example1">example1</string> 
<string name="example2">example2</string> 
<string name="example3" warning="true"><WARNING[[example3]]></string> 
<string name="example4">example4</string> 
<string name="example5"warning="true"><WARNING[[example5]]></string> 
<string name="example6">example6</string> 

我創建的腳本:

file=File.open("./#{ARGV[0]}") 
input = file.read() 
... 
input = input.gsub('%(?<=string \s)\s*name="(\d+)"\s+warning="true">(.+?)(?=</string>)%si', 'name="$1" warning="true"><![Warning[$2]]>') 
... 
f = File.new("test.xml", "w") 
f.write(input)  
f.close 

但它不工作。

+0

您是否嘗試過使用[引入nokogiri(https://github.com/ sparklemotion /引入nokogiri)? –

回答

1

你的XML似乎並沒有成爲一個單一的XML文檔,除非你只粘貼其中的一部分,但事情大致如下的行應該工作:

require 'nokogiri' 

output=File.open("./#{ARGV[0]}").readlines.map do |line| 
    doc = Nokogiri::XML(line) 
    doc.xpath("//string[@warning='true']").map{|m| m.content = "WARNING[[\"{m.text}\"]]"} 
    doc.root.to_s 
end.join("\n") 

f = File.new("test.xml", "w") {|f| f.write(output) } 

微小的修正需要,如果你實際上是通過在一個xml文檔中,但它們相當直接。

0

我怎麼看它:

input.gsub(/(<string name=".*?" warning="true">)(.*?)(<\/string>)/, '\1<WARNING[[\2]]>\3') 

使用參考一組作爲\n其中n是一組數字