How to access attributes using Nokogiri

后端 未结 2 704
情深已故
情深已故 2020-12-09 01:35

I have a simple task of accessing the values of some attributes. This is a simple script that uses Nokogiri::XML::Builder to create a simple XML doc.



        
相关标签:
2条回答
  • 2020-12-09 01:40

    Using Nokogiri::XML::Reader works for your example, but probably isn't the full answer you are looking for (Note that there is no attributes method for Builder).

    reader = Nokogiri::XML::Reader(builder.to_xml)
    reader.read #Moves to next node in document
    reader.attribute("messageId")
    

    Note that if you issued reader.read again and then tried reader.attribute("messageId") the result will be nil since the current node will not have this attribute.

    What you probably want to do is use Nokogiri::XML::Document if you want to search an XML document by attribute.

    doc = Nokogiri::XML(builder.to_xml)
    elems = doc.xpath("//*[@messageId]") #get all elements with an attribute of 'messageId'
    elems[0].attr('messageId') #gets value of attribute of first elem 
    
    0 讨论(0)
  • 2020-12-09 02:00

    Here is a slightly more succinct way to access attributes using Nokogiri (assuming you already have your xml stored in a variable called xml, as covered by @atomicules' answer):

    xml.xpath("//Placement").attr("messageId")
    
    0 讨论(0)
提交回复
热议问题