REXML
The first step to accessing an XML document through the REXML parser is creating the object, passing it the XML document.
var xmlDoc = new REXML(strXML);
Alternatively, the parser object can be created, the XML property set, and the parse method called.
var xmlDoc = new REXML();
...
xmlDoc.XML = strXML;
xmlDoc.parse();
Once the object is created and XML parsed, the following objects, methods, and properties are used to access the XML.
Objects
XMLElement
Each node in the XML document is exposed by an XMLElement object.
XMLElement Properties
- type The type of the element can be:
- element
- text
- comment
- pi
- cdata
- name If the type is "element," the tag name
- childElements[] An array of XMLElements
- parentElement The XML Element's parent XML Element
- text The concatenated value of all text and cdata elements for the element
XMLElement Methods
- getText() Returns all text and cdata of all child elements
- childElement(strElementName) Takes the elements tag name and returns the XMLElement if it's found in the element's children
- attribute(strAttributeName) Takes the attribute name and returns the value, if found. Returns an empty string if the attribute isn't found.
Methods
parse()
The parse method is called for you if you pass the REXML object a string of XML. Otherwise you must call the parse method before you begin working with the XML.
Properties
rootElement
The rootElement property is the entry point, returning the XMLElement for the first node of the document. To work with an XML document the next thing to do after creating the object is to access the rootElement property and use its properties and methods to navigate through the XML.
function ShowXML(strXML) {
var xmlDoc = new REXML(strXML);
alert("The root element " + xmlDoc.rootElement.name + " has " xmlDoc.rootElement.childElements.length + " child elements.");
for (var i=0; i<xmlDoc.rootElement.childElements.length; i++) {
alert("Child element of type " + xmlDoc.rootElement.childElements[i].type);
}
}