我遇到的问题是让所选节点的子节点符合格式。它以某种方式返回给我一个全局选择的格式而不是选定的格式。
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
答案 0 :(得分:2)