Ruby Unit Test : Is this a Valid (well-formed) XML Doc?

后端 未结 3 1948
一向
一向 2021-01-18 14:37

I\'m creating an XML document: I want to unit test at least to make sure it\'s well-formed. So far, I have only been able to approximate this , by using the \'hasElements\'

3条回答
  •  死守一世寂寞
    2021-01-18 14:46

    I use LibXML to perform xml validations, here is the basic usage:

    require 'libxml'
    
    # parse DTD
    dtd = LibXML::XML::Dtd.new(<
    
    EOF
    
    # parse xml document to be validated
    instance = LibXML::XML::Document.file('instance.xml')
    
    # validate
    instance.validate(dtd) # => true | false
    

    from LibXML::DTD

    And this is a link to the LibXML documentation main page.

    If you don't want to use your custom validation rules you can still use a public DTD with something like:

    require 'open-uri'
    dtd =  LibXML::XML::Dtd.new(open("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd").read)
    

    of course you can do much better :)

提交回复
热议问题