简体   繁体   中英

parsing XSD with ruby

Hi i have a XSD that i want to parse. Note that i don't want validate it against a XML but get all enumerations that i have there. For example

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <xsd:simpleType name="fruitNames">
  <xsd:restriction base="xsd:string">
  <xsd:enumeration value="banana" />
  <xsd:enumeration value="apple" />
  <xsd:enumeration value="orange" />
  <xsd:enumeration value="mango" />
 </xsd:restriction>
</xsd:simpleType>
</xsd:schema>

I want to extract the enumeration values.. any idea? I tried to play with XSD::Schema but without success..

XSD is just a flavour of XML so you can use REXML eg

require 'rexml/document'
doc = REXML::Document.new(File.new('yourfile.xsd'))
values = doc.elements.to_a('//xsd:enumeration').map { |el| el.attributes['value'] }
=> ["banana", "apple", "orange", "mango"]

Code sample:

require 'rexml/document'

doc = REXML::Document.new(DATA.read)

REXML::XPath.each(doc, '//xsd:simpleType[@name="fruitNames"]//xsd:enumeration/@value') do |e|
  puts e.value
end

__END__
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <xsd:simpleType name="fruitNames">
  <xsd:restriction base="xsd:string">
  <xsd:enumeration value="banana" />
  <xsd:enumeration value="apple" />
  <xsd:enumeration value="orange" />
  <xsd:enumeration value="mango" />
 </xsd:restriction>
</xsd:simpleType>
</xsd:schema>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM