Wednesday 17 June 2009

Xml demos

Basic XML with scala:
Note you can also use the CDATA command but blogger didn't like me having that here!

def xmlDemo() : Unit = {
val xml = <>my xml
<>1< /val >
<>2< /val >
< /b >
println( xml.length )
}


Filtering XML:
loads XML,
finds how many 'para' tags are in the XML
prints all the 'id' attributes of the 'sect2' tag
Note: \\ means find anywhere \ means find one level down

val xml3 = XML.load("http://www.linux.sgi.com/LDP/authors/template/Sample-HOWTO.xml")
println( (xml3 \\ "para").length )
println( (xml3 \\ "sect2").map(_ \ "@id").map(_.text) )


Transforming XML:

find any nodes which have an 'id=copyright' attribute and remove them

val moveIt = new RewriteRule {
override def transform(n : Node) : NodeSeq = n match {
case e:Elem if (e \"@id").text == "copyright" => NodeSeq.Empty
case e => e
}
}
println( new RuleTransformer(moveIt).transform(xml3) )

No comments:

Post a Comment