Search code examples
xpathcrystal-lang

Crystal xpath library or implementation


Is there any way to use xpath when parsing an HTML file ?

I am looking for a Ruby Nokogiri equivalent but Crystagiri does not implement it ( yet ? ). Also tried myhtml and modest but to no avail.


Solution

  • You don't need to use external libraries for this! Crystal has an XML module built in, which has xpath support.

    Here's a basic example:

    nodes = XML.parse_html(html_content)
    nodes.xpath_nodes(query).each do |node|
        # do something
    end
    

    where html_content is your HTML as a string, and query is your xpath query.