Skip to content

Support XML Namespaces#23

Open
takahashim wants to merge 1 commit into
serpapi:masterfrom
takahashim:add-namespace-api
Open

Support XML Namespaces#23
takahashim wants to merge 1 commit into
serpapi:masterfrom
takahashim:add-namespace-api

Conversation

@takahashim

Copy link
Copy Markdown
Contributor

This PR adds a Nokogiri-style XML Namespace API to Nokolexbor.

Lexbor already keeps namespace information internally; this PR exposes that information through Nokolexbor's Ruby API and makes it available to XPath namespace resolution.

This enables proper handling of HTML documents that contain SVG, MathML, or other namespaced content.

Example

require "nokolexbor"

html = <<~HTML
  <!doctype html>
  <html>
    <body>
      <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
        <circle id="dot" cx="50" cy="50" r="10" fill="red"></circle>
      </svg>
    </body>
  </html>
HTML

doc = Nokolexbor::HTML(html)

circle = doc.at_xpath(
  "//svg:circle",
  "svg" => "http://www.w3.org/2000/svg"
)

puts circle["fill"]         # => red
puts circle.namespace.href  # => http://www.w3.org/2000/svg

Compatibility

This PR adds support for the common Nokogiri namespace APIs in Nokolexbor:

  • Nokolexbor::Namespace provides prefix, href, and document, mirroring Nokogiri::XML::Namespace.
  • Node#namespace, #namespace_scopes, #namespaces, #namespace_definitions, and #add_namespace_definition provide Nokogiri-compatible namespace accessors.
  • XPath queries with explicit namespace prefixes, such as at_xpath("//svg:circle", "svg" => "..."), now work for elements in default namespaces such as xmlns="http://www.w3.org/2000/svg".

The changes are additive. No existing Nokolexbor API is intentionally changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant