Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find node by name by using Nokogiri

Trying to find nodes by name. Here is my xml:

<Project>
 <ItemGroup>
    <Compile Include="..\..\CommonAssemblyInfo.cs">
      <Link>Properties\CommonAssemblyInfo.cs</Link>
    </Compile>
    <Compile Include="Global.asax.cs">
      <DependentUpon>Global.asax</DependentUpon>
    </Compile>
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\myproject1.csproj">
      <Name>Myproject1</Name>
    </ProjectReference>
    <ProjectReference Include="..\Myproject2.csproj">
      <Name>MyProject2</Name>
    </ProjectReference>
    <ProjectReference Include="..\myproject3.csproj">
      <Name>MyProject3</Name>
    </ProjectReference>
 </ItemGroup>
</Project>

Here is my code to get all Name nodes from above XML:

  f = File.open(projectpath)
  @doc = Nokogiri::XML(f)
  #print f.read
  names = @doc.xpath("Name")
  print names

  f.close  

My code got nothing from the XML search.

like image 877
icn Avatar asked Jan 03 '12 23:01

icn


1 Answers

You need the wildcard path construct (//), otherwise you are just looking at the elements at the root level.

names = @doc.xpath("//Name")

Perhaps you were thinking of CSS searching, which would use exactly the string you supplied:

names = @doc.css("Name")

Or maybe you have used the search method which tries to make an educated guess whether you are using CSS or XPath. It would work properly in this case:

names = @doc.search("Name")
like image 109
Mark Thomas Avatar answered Sep 28 '22 08:09

Mark Thomas