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



我在获取与格式匹配的选定节点的子节点时遇到问题。它以某种方式向我返回格式的全局选择,而不是从所选格式返回。

  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
  • 表示匹配根之后的任何位置
  • .//表示匹配当前节点之后的任何位置。

相关内容

  • 没有找到相关文章

最新更新