Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching with multiline XML case

I must be doing some stupid mistake. I have a server that returns the XML <a><b>123</b></a> and now I would like to match against that XML. So I write something like

xml match {
  case <a><b>{_}</b></a> => true
}

This works as long as I do not have to deal with multi-line XML literals. So the important thing is that the server sends me the whole XML as a one-liner. The XML is large enough to explode a single line of code, but I can not figure out how to get this to work.

Server sends <a><b>123</b><c>123</c><d>123</d><e>123</e><f>123</f></a> and I would like to do this:

xml match {
  case <a>
    <b>{_}</b>
    <c>{valueOfC}</c>
    <d>{_}</d>
    <e>{_}</e>
    <f>{_}</f>
  </a> => valueOfC
}

But I always get a MatchError. If I write everything in a single line it works. So the question is: how can I match XML while writing human-readable code?

I have of course tried to find an answer via Google. Funny enough all examples are one-liners or work recursive.

like image 577
Joa Ebert Avatar asked Jan 12 '10 20:01

Joa Ebert


2 Answers

XML with and without newlines and other whitespace is not considered the same using "match". If you use scala.xml.Utility.trim, you can remove whitespace. (You probably want to trim both your input and what the server gives you unless you're positive the server will send you no whitespace.)

like image 191
Rex Kerr Avatar answered Oct 24 '22 11:10

Rex Kerr


Perhaps you could try something like:

x match {
  case <a><b>{n @ _*}</b></a> => println(n)
}

I'm not saying it will work... but it might

like image 1
Don Mackenzie Avatar answered Oct 24 '22 11:10

Don Mackenzie