Class: XmlUtils::XPath
- Inherits:
-
Object
- Object
- XmlUtils::XPath
- Defined in:
- lib/xmlutils/xpath.rb
Class Method Summary collapse
- .apply_predicate(candidates, predicate) ⇒ Object
- .each(element, path, &block) ⇒ Object
- .first(element, path) ⇒ Object
- .match(element, path) ⇒ Object
- .match_step(node, step) ⇒ Object
Class Method Details
.apply_predicate(candidates, predicate) ⇒ Object
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
# File 'lib/xmlutils/xpath.rb', line 85 def self.apply_predicate(candidates, predicate) if predicate =~ /^\d+$/ idx = predicate.to_i - 1 idx >= 0 && candidates[idx] ? [candidates[idx]] : [] elsif predicate =~ /^@(\S+)$/ attr_name = $1 candidates.select { |c| c.has_attribute?(attr_name) } elsif predicate =~ /^@(\S+)\s*=\s*['"]([^'"]*)['"]$/ attr_name = $1 attr_value = $2 candidates.select { |c| c[attr_name] == attr_value } elsif predicate =~ /^contains\(\s*(\S+)\s*,\s*['"]([^'"]*)['"]\s*\)$/ candidates # Simplified: not fully implemented else candidates end end |
.each(element, path, &block) ⇒ Object
42 43 44 |
# File 'lib/xmlutils/xpath.rb', line 42 def self.each(element, path, &block) match(element, path).each(&block) end |
.first(element, path) ⇒ Object
38 39 40 |
# File 'lib/xmlutils/xpath.rb', line 38 def self.first(element, path) match(element, path).first end |
.match(element, path) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/xmlutils/xpath.rb', line 20 def self.match(element, path) return [element] if path.nil? || path.strip.empty? || path == '.' return [element] if path == '/' nodes = [element] parts = path.split('/').reject(&:empty?) parts.each do |part| new_nodes = [] nodes.each do |node| new_nodes.concat(match_step(node, part)) end nodes = new_nodes end nodes end |
.match_step(node, step) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/xmlutils/xpath.rb', line 46 def self.match_step(node, step) return [] unless node.is_a?(Element) || node.is_a?(Document) if step == '*' return node.children.select { |c| c.is_a?(Element) } end if step == '..' return node.parent ? [node.parent] : [] end if step.start_with?('@') attr_name = step[1..] if node.is_a?(Element) attr = node.attribute(attr_name) return attr ? [attr] : [] end return [] end if step.include?('[') name = step[/^[^\[]+/] predicate = step[/\[(.*?)\]/, 1] else name = step predicate = nil end if node.is_a?(Document) candidates = node.children.select { |c| c.is_a?(Element) && c.name == name } else candidates = node.children.select { |c| c.is_a?(Element) && c.name == name } end return candidates unless predicate apply_predicate(candidates, predicate) end |