Class: XmlSchemaMapper::Parser
- Inherits:
-
Object
- Object
- XmlSchemaMapper::Parser
- Defined in:
- lib/xml_schema_mapper/parser.rb
Instance Method Summary collapse
- #content_for(node) ⇒ Object
- #document(xml) ⇒ Object
- #get_node_by_xpath(element, xml) ⇒ Object
- #get_nodes_by_xpath(element, xml) ⇒ Object
-
#initialize(klass) ⇒ Parser
constructor
A new instance of Parser.
- #parse(xml) ⇒ Object
- #write_array_element(element, instance, xml) ⇒ Object
- #write_element(element, instance, xml) ⇒ Object
Constructor Details
#initialize(klass) ⇒ Parser
Returns a new instance of Parser.
3 4 5 6 |
# File 'lib/xml_schema_mapper/parser.rb', line 3 def initialize(klass) @klass = klass @module = resolve_module end |
Instance Method Details
#content_for(node) ⇒ Object
43 44 45 |
# File 'lib/xml_schema_mapper/parser.rb', line 43 def content_for(node) node.content if node end |
#document(xml) ⇒ Object
63 64 65 66 |
# File 'lib/xml_schema_mapper/parser.rb', line 63 def document(xml) return xml if xml.is_a?(Nokogiri::XML::Node) Nokogiri::XML(xml).root end |
#get_node_by_xpath(element, xml) ⇒ Object
47 48 49 50 51 52 53 |
# File 'lib/xml_schema_mapper/parser.rb', line 47 def get_node_by_xpath(element, xml) if element.namespace xml.at_xpath("./foo:#{element.name}", { 'foo' => element.namespace }) else xml.at_xpath("./#{element.name}") end end |
#get_nodes_by_xpath(element, xml) ⇒ Object
55 56 57 58 59 60 61 |
# File 'lib/xml_schema_mapper/parser.rb', line 55 def get_nodes_by_xpath(element, xml) if element.namespace xml.xpath("./foo:#{element.name}", { 'foo' => element.namespace }) else xml.xpath("./#{element.name}") end end |
#parse(xml) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/xml_schema_mapper/parser.rb', line 8 def parse(xml) instance = @klass.new xml = document(xml) @klass.elements.each do |e| if e.array? write_array_element(e, instance, xml) else write_element(e, instance, xml) end end instance end |
#write_array_element(element, instance, xml) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/xml_schema_mapper/parser.rb', line 30 def write_array_element(element, instance, xml) instance.send(element.writer, []) if element.simple? get_nodes_by_xpath(element, xml).each do |node| instance.send(element.reader) << content_for(node) if instance.respond_to?(element.writer) end else get_nodes_by_xpath(element, xml).each do |node| instance.send(element.reader) << resolve_element_parser(element).parse(node) if instance.respond_to?(element.writer) end end end |
#write_element(element, instance, xml) ⇒ Object
21 22 23 24 25 26 27 28 |
# File 'lib/xml_schema_mapper/parser.rb', line 21 def write_element(element, instance, xml) node = get_node_by_xpath(element, xml) if element.simple? instance.send(element.writer, content_for(node)) if instance.respond_to?(element.writer) else instance.send(element.writer, resolve_element_parser(element).parse(node)) if instance.respond_to?(element.writer) end end |