开发者

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

开发者 https://www.devze.com 2022-12-31 18:01 出处:网络
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.

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.root )
  end
end

Where my XML looks 开发者_Python百科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?


Currently, I've found a way to make this work by creating an artificial root element and doing a series of insertions / deletions like the following:

  doc = REXML::Document.new( "<include>#{data}</include>" )
  previous_element = element
  doc.root.elements.each do |child|
    element.parent.insert_after( previous_element, child )
    previous_element = child
  end
  element.parent.delete( element )

It makes me feel like there must be a better way.

0

精彩评论

暂无评论...
验证码 换一张
取 消