Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

11.8. Substituting XML Entities

Problem

You've parsed a document that contains internal XML entities. You want to substitute the entities in the document for their values.

Solution

To perform entity substitution on a specific text element, call its value method. If it's the first text element of its parent, you can call text on the parent instead.

Here's a simple document that defines and uses two entities in a single text node. We can substitute those entities for their values without changing the document itself:

	require 'rexml/document'

	str = %{<?xml version="1.0"?>
	<!DOCTYPE doc [
	  <!ENTITY product 'Stargaze'>
	  <!ENTITY version '2.3'>
	]>
	<doc>
	 &product; v&version; is the most advanced astronomy product on the market.
	</doc>}
	doc = REXML::Document.new str

	doc.root.children[0].value
	# => "\n Stargaze v2.3 is the most advanced astronomy product on the market.\n"
	doc.root.text
	# => "\n Stargaze v2.3 is the most advanced astronomy product on the market.\n"

	doc.root.children[0].to_s
	# => "\n &product; v&version; is the most advanced astronomy product on the market.\n"
	doc.root.write
	# <doc>
	# &product; v&version; is the most advanced astronomy program on the market.
	# </doc>

Discussion

Internal XML entities are often used to factor out data that changes a lot, like dates or version numbers. But REXML only provides a convenient way to perform substitution on a single text node. What if you want to perform substitutions throughout the entire document?

When you call Document#write to send ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required