Xml View

lua-users home
wiki

xmlview: convenient access to XML trees

(This is part of LazyKit.)

This package is a work in progress for XmlTree. Quick summary:

xstring(node)

Returns the immediate string contents of node (which may be either a tree or, trivially, a string.) Returns nil,errormessage if node is a tree with mixed content.

xtext(node)

Recursively returns the string contents of node, descending into any child elements.

View objects

Views provide easy random access to the children of a XmlTree. They are currently read-only.

The current implementation completely populates them on first access, but lazy implementations are possible.

xmlview.string(tree)

Create a string view on tree. The view contains all immediate children of tree that have unique element names and do not contain mixed content. Accessing names that are not unique or have mixed content results in an error. Example:

<logentry>

  <type>INFO</info>

  <time>12:50</time>

  <receivedfrom>upstream1</receivedfrom>

  <receivedfrom>upstream2</receivedfrom>

  <body>This is a <b>test message</b></body>

  <empty/>

</logentry>



tree=lxptree.parsestring(s)

sv = xmlview.string(tree)

print(sv.type)          -- "INFO"

print(sv.time)          -- "12:50"

print(sv.empty)         -- ""

print(sv.receivedfrom)  -- error "contains duplicate content"

print(sv.body)          -- error "contains mixed content" 

xmlview.text(tree)

Create a text view on tree. The view contains all immediate children of tree that have unique element names. xtext is called on those children, providing the recursive character data content of those nodes. Accessing names that are not unique results in an error.

xmlview.elements(tree)

Create an elements view on tree. The view contains a list of all child element trees with the given name. Example:

ev = xmlview.elements(tree)

ev.type => {{name="type", "INFO", n=1}, n=1}

ev.receivedfrom => {

  {name="receivedfrom", "upstream1", n=1}, 

  {name="receivedfrom", "upstream2", n=1},

  n=2

} 

What's missing

element would provide named elements if they were unique.

firststring, firsttext, and firstelement would be views that did not have to iterate through the entire tree, as they would not have to guarantee uniqueness. This could be friendlier to lazy trees.


RecentChanges · preferences
edit · history
Last edited February 28, 2004 11:32 pm GMT (diff)