Injecting an XML fragment into the current document from an external file

Posted by makenai on Stack Overflow See other posts from Stack Overflow or by makenai
Published on 2010-05-25T06:01:02Z Indexed on 2010/05/25 6:21 UTC
Read the original article Hit count: 319

Filed under:
|
|

I'm currently parsing an XML file using REXML and trying to come up with a way of inserting an XML fragment from an internal file.

Currently, I'm using some logic like the following:

doc.elements.each('//include') do |element|
  handleInclude( element )
end

def handleInclude( element )      
  if filename = element.attributes['file']
    data = File.open( filename ).read
    doc = REXML::Document.new( data )
    element.parent.replace_child( element, doc )
  end
end

Where my XML looks like the following:

<include file="test.xml" />

But this seems a little bit clunky, and I'm worried that REXML might not always parse XML fragments correctly due to absence of a proper root node in some cases. Is there a better way of doing this?

Concern #2: REXML seems not to pick up my changes after I replace elements. For example, after making a change:

doc.elements.each('rootNode/*') do |element|
end

..picks up neither the original element I replaced, nor the one I replaced it with. Is there some trick to getting REXML to rescan its' tree?

© Stack Overflow or respective owner

Related posts about Xml

Related posts about ruby