alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Play Framework/Scala example source code file (XPathSpec.scala)

This example Play Framework source code file (XPathSpec.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Play Framework (and Scala) source code examples by using tags.

All credit for the original source code belongs to Play Framework; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Play Framework tags/keywords

lib, library, map, play, play framework, specification, xpath, xpathspec

The XPathSpec.scala Play Framework example source code

/*
 * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
 */
package play.libs

import org.specs2.mutable.Specification
import scala.collection.JavaConverters._


object XPathSpec extends Specification {
  //XPathFactory.newInstance() used internally by XPath is not thread safe so forcing sequential execution
  sequential

  val xmlWithNamespace = XML.fromString("""<x:foo xmlns:x="http://foo.com/"><x:bar><x:baz>hey</x:baz></x:bar></x:foo>""")
  val xmlWithoutNamespace = XML.fromString("""<foo><bar><baz>hey</baz></bar><bizz></bizz><bizz></bizz></foo>""")

  "XPath" should {
    "ignore already bound namespaces" in {
      val ns = Map("x" -> "http://foo.com/", "ns" -> "http://www.w3.org/XML/1998/namespace", "y" -> "http://foo.com/")
      XPath.selectText("//x:baz", xmlWithNamespace, ns.asJava) must not(throwAn[UnsupportedOperationException])
    }

    "find text with namespace" in {
      val text = XPath.selectText("//x:baz", xmlWithNamespace, Map("ns" -> "http://www.w3.org/XML/1998/namespace", "x" -> "http://foo.com/").asJava)
      text must_== "hey"
    }

    "find text without namespace" in {
      val text = XPath.selectText("//baz", xmlWithoutNamespace, null)
      text must_== "hey"
    }

    "find node with namespace" in {
      val node = XPath.selectNode("//x:baz", xmlWithNamespace, Map("ns" -> "http://www.w3.org/XML/1998/namespace", "x" -> "http://foo.com/").asJava)
      node.getNodeName must_== "x:baz"
    }

    "find nodes" in {
      val nodeList = XPath.selectNodes("//bizz", xmlWithoutNamespace, null)
      nodeList.getLength === 2
    }
  }
}

Other Play Framework source code examples

Here is a short list of links related to this Play Framework XPathSpec.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.