2012-12-26 68 views
3

我正在解析pptx文件並遇到問題。這是源XML的一個樣本:使用名稱空間獲取XML屬性的值

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> 
    <p:sldMasterIdLst> 
    <p:sldMasterId id="2147483648" r:id="rId2"/> 
    </p:sldMasterIdLst> 
    <p:sldIdLst> 
    <p:sldId id="256" r:id="rId3"/> 
    </p:sldIdLst> 
    <p:sldSz cx="10080625" cy="7559675"/> 
    <p:notesSz cx="7772400" cy="10058400"/> 
</p:presentation> 

我需要得到在sldMasterId標籤的r:id屬性值。

doc = Nokogiri::XML(path_to_pptx) 
doc.xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId').attr('id').value 

回報2147483648但我需要rId2,這是r:id屬性值。

我發現attribute_with_ns(name, namespace)方法,但

doc.xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId').attribute_with_ns('id', 'r') 

收益爲零。

回答

1

http://nokogiri.org/Nokogiri/XML/Node.html#method-i-attributes

如果需要使用相同的名稱來區分屬性,不同的命名空間使用attribute_nodes代替。

doc.xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId').each do |element| 
    element.attribute_nodes().select do |node| 
    puts node if node.namespace && node.namespace.prefix == "r" 
    end 
end 
1

您可以參考在你的XPath以同樣的方式屬性的命名空間中引用元素命名空間:

doc.xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId/@r:id') 

如果你想使用attribute_with_ns,您需要使用實際的名稱空間,不只是前綴

doc.at_xpath('p:presentation/p:sldMasterIdLst/p:sldMasterId') 
    .attribute_with_ns('id', "http://schemas.openxmlformats.org/officeDocument/2006/relationships") 
相關問題