2015-10-06 68 views
1

TextMate片段(.tmSnippet)通常看起來像這樣,而一些鍵/字符串對是可選的,可以在任何位置。解析Nokogiri的TextMate片段

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<dict> 
     <key>content</key> 
     <string>${1:the actual snippet}</string> 
     <key>tabTrigger</key> 
     <string>my_trigger</string> 
     <key>name</key> 
     <string>This is my Snippet's name</string> 
     <key>scope</key> 
     <string>source.js</string> 
     <key>uuid</key> 
     <string>6C2985F1-9BB8-43D7-A85C-1006B2932A0D</string> 
</dict> 
</plist> 

我試圖分析此使用引入nokogiri,但由於標籤都是<key><string>和每個鍵/串線對可以改變的立場,我不知道該怎麼做。我在scopetabTrigger,contentname之後。

+0

我沒有任何東西可以添加到接受的答案中,但是您是否知道有解析Apple's PropertyList格式的Gem? [bleything/plist](https://github.com/bleything/plist):通用屬性列表操作庫 –

回答

1

假設dict節點的子節點只是key - string雙,這樣的:

require 'nokogiri' 

kws = %w{ scope tabTrigger content name } 

doc = Nokogiri::XML(File.read('a.tmsnippet')) 

doc.xpath('//dict').each do | dict_node | 
    dict_node.element_children.map(&:content).each_slice(2) do | k, v | 
    next unless kws.include? k 
    puts "#{k} -> #{v}" 
    end 
end 

產生

"content -> ${1:the actual snippet} 
tabTrigger -> my_trigger 
name -> This is my Snippet's name 
scope -> source.js" 

否則,你需要對節點類型多一些邏輯看着前他們的內容。