0

I have the following string i loaded by typesafe ConfigFactory.

Conf.conf:

xpath {
    test = """"region"/"city"/"street"/"apartment""""
}

Then i convert it to suitable format (back slash to forward slash "region"\"city"\"street"\"apartment"):

val conf = ConfigFactory.load("Conf.conf").getString("xpath.test")
val test = conf.replace("/","\\")

I have XML file:

val xml_file = XML.load("PATHtoXML")

so that to further find value of "test" in "xml_file". In general it works like : (xml_file \ "xx" \ "yyy" \ "dddd").text. However I'm stuck to getting value in my case:

val res = (xml_file \\ test).text
println(s"Result -> ${res}")

it returns nothing.

Would you please give me some hints to solve it.

many thanks!

27P
  • 1,183
  • 16
  • 22

1 Answers1

0

If it is not against your requirements, you can use standard Java library to parse your XML file. To my opinion, it is more flexible than Scala XML, because as far as I know, with the latter, you could not use easily an XPath expression as a String. You can just iterate with \\ and \ operators, like :

val res: String = (xml \\ "region" \ "city" \ "street" \ "apartment").text

With Java library, you can do the following (example based on the accepted answer of the SO post I provided above) :

import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathFactory

val factory = DocumentBuilderFactory.newInstance
val builder = factory.newDocumentBuilder
val doc = builder.parse("PATHtoXML")

val xPathfactory = XPathFactory.newInstance
val xpath = xPathfactory.newXPath
val conf = "region/city/street/apartment"
val expr = xpath.compile(conf)

val res = expr.evaluate(doc)
println(s"Result -> ${res}")

You can also define your Conf.conf like :

xpath {
    test = "region/city/street/apartment"
}

And use it by replacing conf above with :

val conf = ConfigFactory.load("Conf.conf").getString("xpath.test")
norbjd
  • 10,166
  • 4
  • 45
  • 80