tags:

views:

25

answers:

1

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 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?

+1  A: 

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.

makenai
do you have to use ruby? Would java or C# work?
vtd-xml-author