Search code examples
rubyxmlnokogiriparsexml

Avoiding Nokogiri::XML::XPath::SyntaxError: ERROR: Undefined namespace prefix


I get the error "Nokogiri::XML::XPath::SyntaxError: ERROR: Undefined namespace prefix" when I do this:

 doc.search('//text()[not(ancestor::w:delText]')

Based on this answer: How do I use xpath on nodes with a prefix but without a namespace?

*[name()="w:delText"] 

can sort of solve the problem. But how do I do something similar like this to avoid the namespace error:

doc.search('//text()[not(ancestor::*[name()="w:delText"]')

Solution

  • I ended up solving the problem by editing the XML file and adding the namespaces in the root. Here is an example:

      temp = Nokogiri::XML(@document_xml)
      temp.root['xmlns:w'] = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"      
      @doc = Nokogiri::XML(temp.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XML))