我有一個 TMX 翻譯記憶庫檔案,我需要對其進行決議才能將其匯入到新的資料庫中。我正在使用 Ruby Nokogiri。這是 TMX (xml) 結構:
<body>
<tu creationdate="20181001T113609Z" creationid="some_user">
<prop type="Att::Attribute1">Value1</prop>
<prop type="Txt::Attribute2">Value2</prop>
<prop type="Txt::Attribute3">Value3</prop>
<prop type="Txt::Attribute4">Value4</prop>
<tuv xml:lang="EN-US">
<seg>Testing</seg>
</tuv>
<tuv xml:lang="SL">
<seg>Testiranje</seg>
</tuv>
</tu>
</body>
為簡單起見,我在此處僅包含 1 個 TU 節點。
這是我當前的腳本:
require 'nokogiri'
doc = File.open("test_for_import.xml") { |f| Nokogiri::XML(f) }
doc.xpath('//tu').each do |x|
puts "Creation date: " x.attributes["creationdate"]
puts "User: " x.attributes["creationid"]
x.children.each do |y|
puts y.children
end
end
這產生以下結果:
Creation date: 20181001T113609Z
User: some_user
Value1
Value2
Value3
Value4
<seg>Testing</seg>
<seg>Testiranje</seg>
我需要做的是搜索Attribute1它的相應值并分配給一個變數。然后,在新資料庫中創建翻譯記錄時,這些將用作屬性。我需要同樣的seg來獲取源代碼和翻譯。我不想依賴順序,即使它應該/總是相同的。
繼續的最佳方式是什么?所有元素都屬于類Nokogiri::XML::NodeSet 。即使在查看了檔案之后,我仍然被卡住了。
有人可以幫忙嗎?
最好的,塞巴斯蒂安
uj5u.com熱心網友回復:
像這樣遍歷節點樹的最簡單方法是使用 XPath。您已經使用 XPath 來獲取頂級tu元素,但是您可以進一步擴展 XPath 查詢以獲取您正在尋找的特定元素。
DevHints 上有一個方便的備忘單,說明您可以使用 XPath 做什么。
相對于x指向tu元素的變數,以下是您要使用的 XPath:
prop[@type="Att::Attribute1"]尋找你prop的屬性 1//seg或tuv/seg用于查找seg元素
這是使用這些 XPath 的完整代碼示例。該at_xpath方法回傳一個結果,而該xpath方法回傳所有結果。
require 'nokogiri'
doc = File.open("test_for_import.xml") { |f| Nokogiri::XML(f) }
doc.xpath('//tu').each do |x|
puts "Creation date: " x.attributes["creationdate"]
puts "User: " x.attributes["creationid"]
# Get Attribute 1
# There should only be one result for this, so using `at_xpath`
attr1 = x.at_xpath('prop[@type="Att::Attribute1"]')
puts "Attribute 1: " attr1.text
# Get each seg
# There will be many results, so using `xpath`
segs = x.xpath('//seg')
segs.each do |seg|
puts "Seg: " seg.text
end
end
這輸出:
Creation date: 20181001T113609Z
User: some_user
Attribute 1: Value1
Seg: Testing
Seg: Testiranje
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359998.html
