如何使用xpath?i从所选节点的子节点中进行选择

时间:2012-07-02 07:44:52

标签: ruby-on-rails ruby xpath nokogiri

我遇到的问题是让所选节点的子节点符合格式。它以某种方式返回给我一个全局选择的格式而不是选定的格式。

  doc = Nokogiri::XML(f)
  group_with_obj_and_unit =  doc.xpath("/x:svg/x:g[x:text[matches(text(),'^#[0123456789]+\-[0123456789][\/[0123456789]+]*$')]][x:text[not(matches(text(),'^#[0123456789]+\-[0123456789][\/[0123456789]+]*$'))]][x:path or x:rect or x:circle or x:ellipse or x:polyline or x:polygon]", FindWithRegex, "x" => "http://www.w3.org/2000/svg")
  group_with_obj_and_unit.each do |matched_group|
    text_object = matched_group.xpath("//x:g/x:text[matches(text(),'^#[0123456789]+\-[0123456789][\/[0123456789]+]*$')]", FindWithRegex, "x" => "http://www.w3.org/2000/svg")
    object = matched_group.xpath("//x:g/x:path | /x:svg/x:g/x:rect | /x:svg/x:g/x:circle | /x:svg/x:g/x:ellipse | /x:svg/x:g/x:polyline | /x:svg/x:g/x:polygon", "x" => "http://www.w3.org/2000/svg")

    #object['id'] = text_object.text
  end

编辑

在@pguardiario

建议之后
  def run!
    fileContent = File.new @file_path, "r"
    file = File.open @file_path, "r+"
    doc = Nokogiri::XML(fileContent)

    group_with_obj_and_unit =  doc.xpath("/x:svg/x:g[x:text[matches(text(),'^#[0123456789]+\-[0123456789][\/[0123456789]+]*$')]][x:text[not(matches(text(),'^#[0123456789]+\-[0123456789][\/[0123456789]+]*$'))]][x:path or x:rect or x:circle or x:ellipse or x:polyline or x:polygon]", FindWithRegex, "x" => "http://www.w3.org/2000/svg")
    group_with_obj_and_unit.each do |matched_group|
      #find the text object and the object of the selected node
      text_object = matched_group.at_xpath("./x:text[matches(text(),'^#[0123456789]+\-[0123456789][\/[0123456789]+]*$')]", FindWithRegex, "x" => "http://www.w3.org/2000/svg")
      object = matched_group.at_xpath("./x:path | ./x:rect | ./x:circle | ./x:ellipse | ./x:polyline | ./x:polygon", "x" => "http://www.w3.org/2000/svg")

      object['id'] = text_object.text
    end
    file.write doc.to_xml

    file.close
  end

1 个答案:

答案 0 :(得分:2)

  • //表示匹配根
  • 之后的任何位置
  • .//表示匹配当前节点之后的任何位置。