The XPath Access Mechanism

The XPath part of the solution makes accessing the elements within the XML document much easier than a traditional event-driven or even DOM-based parser. To use the XPath interface is simplicity itself. For example, to get a list of all the subelements, you need to do is access the elements property of the parent element. The each() method accepts an XPath definition that in turn returns a list of all the subelements that it finds.

For example, you can work through all the items using this: xmldoc.elements.eachC'Vitem") { |e1ement| print element } which in turn generates this:

You can also use XPath to access a specific element. For example, to extract the element with a code attribute matching 1001, you would use this: doc.root.elements[,l[@code=l10011]"]

A list of the fully supported XPath constructs is shown in Table 21.1.

TABLE 21.1: XPath Constructs Supported by REXML

Construct

Description

/

root element.

Self.

Parent element.

*

All child elements.

//

All document elements.

//child

All child elements in document matching child.

parent//chi1d

All child elements of the element parent.

parent/child

All child elements of parent.

[...]

All predicates (attribute, index, or text) matching supplied text. You can prefix a spe

cific element with @; for instance, to search for an attribute match use ©attribute.

[...][...]

Compound predicates.

element

Child element element.

0 0

Post a comment

  • Receive news updates via email from this site