How to get first level children for xml in nokogiri

55 views
Skip to first unread message

Rohit Dumbre

unread,
Apr 1, 2017, 6:17:08 PM4/1/17
to nokogiri-talk

I am trying to parse the pom file using Nokogiri and I want to get first level of child nodes.

My pom file looks something like this

<project xmlns="some.maven.link">
   <parent>
     <groupId>parent.jar</groupId>
     <artifactId>parent-jar</artifactId>  
   </parent>         
   <groupId>child.jar</groupId>
   <artifactId>child-jar</artifactId>
 </project>

I am trying to fetch the artifactId "child-jar but the xpath that I am using possibly is incorrect and its fetching me parent.jar as the first occurence.

This is my ruby code

@pom = Nokogiri::XML(File.open(file_path))
p @pom.xpath("/project/artifactId", project"=>"http://maven.apache.org/POM/4.0.0")[0].text

I can access the second element but that just would be a hack.

Mike Dalessio

unread,
Apr 10, 2017, 7:50:07 AM4/10/17
to nokogiri-talk
require 'nokogiri'

doc = <<-EOX
<project xmlns="some.maven.link">
   <parent>
     <groupId>parent.jar</groupId>
     <artifactId>parent-jar</artifactId>  
   </parent>         
   <groupId>child.jar</groupId>
   <artifactId>child-jar</artifactId>
 </project>
EOX

pom = Nokogiri::XML doc

puts pom.xpath("/xmlns:project/xmlns:artifactId", "xmlns" => "some.maven.link")
# => "child-jar"


--
You received this message because you are subscribed to the Google Groups "nokogiri-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nokogiri-talk+unsubscribe@googlegroups.com.
To post to this group, send email to nokogi...@googlegroups.com.
Visit this group at https://groups.google.com/group/nokogiri-talk.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages