Validating XML against a schema in Ruby

nokalexander

New Member
I need to write a Ruby script to validate XML responses against a master XML schema template.Say for example, an example XML response coming from the backend for a controller is:\[code\]<a> <ID>TestID</ID> <Name>NameTest</Name> <Description/> <DisplayName>DisplayNameTest</DisplayName></a>\[/code\]and I have an XML schema template which has one of the section looks like:\[code\]<Object name = "a"> <property name = "ID" optional="true"/> <property name = "Name" optional="true"/> <property name="visibility" /> <property name="Description" optional="true" /> <property name="DisplayName" optional="true" /> </Object>\[/code\]Things I want to validate against the schema template is: [*]If the optional attribute tag is set to true, this tag is mandatory and must be present in the response.[*]The tag orders need to follow the tag orders in the schema template.If either of the condition doesn't comply, return false.Some piece of the codes I have now is (probably there are a lot of ways to better do this):\[code\]response_xml = REXML::Document.new(response_xml)response_xml_root = response_xml.root.name.to_s.chompxml_api_meta = REXML::Document.new(File.read('Schema.xml'))response_xml_array = response_xml.root.elements.to_a.collect { |e| e.name }@api_meta_array = []xml_api_meta.elements.each('ApiMeta/Object') do |element| if element.attributes["name"] == response_xml_root element.elements.each do |children| @api_meta_array.push children.attributes["name"] end endend\[/code\]My idea is to collect all the tag names from response XML and push them into an array \[code\]@response_xml_array\[/code\] and do the same thing for the schema and push all the tag found in an array \[code\]@api_meta_array\[/code\]. How can I validate the sequence and whether it is optional or not?
 
Back
Top