Scala XML: test for node existence and value

I am parsing a series of XML responses from an external data store. During which I must check for the existence of a child node and - if it exists - check its value. For this, I have the following code:

...
  val properties = for {
    val row <- root \\ "ResultDescription"
    val cond:Boolean = checkDetectionNode(row) match {
      case Some(nodeseq) => {
          val txt = nodeseq.text.toLowerCase
          if (txt contains "non-detect")
            false
          else
            true
      }
      case None => true
    }
    if (cond)
    val name = (row \ "CharacteristicName").text
    if (charNameList.exists(s => s == name) == false)
  } yield {
    getObservedProperty(name) match {
      case Some(property) => {
          charNameList = name :: charNameList
          property
      }
    }
  }
...

checkDetectionNode is defined as such:

private def checkDetectionNode(row: scala.xml.NodeSeq) : Option[scala.xml.NodeSeq] = {
  if ((row \ "ResultDetectionConditionText") != null)
    Some[scala.xml.NodeSeq]((row \ "ResultDetectionConditionText"))
  else
    None
}

" " val name.... , Scala ( OO/). Scala , , Java -. , , Scala, . , .

, - , -, ( , ). , , . , , , - .

+5
3

xml - . , if (cond) , , , , , "" .

:

val l = List(1,2,3,4,5)

val r = for {
    i <- l 
      if (i > 2)
    x <- Some(i * 2)
  } yield x

(6,8,10), .

val r = for {
    val i <- l if (i > 2)
    val x <- Some(i * 2)
  } yield x

,

val r = for {
    val i <- l 
    if (i > 2)
    val x <- Some(i * 2)
  } yield x

error: illegal start of simple expression
  val x <- Some(i * 2)

val (Pattern1 '<r - Expr [Guard]), . , vals for, .

+1

, , (row \ "ResultDetectionConditionText") null, - NodeSeq ( Scala , , null, , , ). , Some, , , , . != null .nonEmpty .

, :

val cond = (row \ "ResultDetectionConditionText").exists(
  _.text.toLowerCase contains "non-detect"
)

: NodeSeq, "Result...", , , NodeSeq node, "non-detect". , , , , , - -, , - :

val row = <row>
  <ResultDetectionConditionText>non-d</ResultDetectionConditionText>
  <ResultDetectionConditionText>etect</ResultDetectionConditionText>
</row>

.

"illegal start of simple expression" - ​​ . , , name, , , . - Option:

val name = if (cond) Some((row \ "CharacteristicName").text) else None

, name, .

+3

if (cond)should follow the expression. In Scala, it is ifmore like a ternary operator in Java: it is an expression, not a statement. A variable declaration is not an expression (as in Java), so you cannot have an if part valin it then.

Honestly, I cannot figure out what you want to achieve there, so I cannot offer a syntactically correct alternative that makes sense. But if you have more logic, which depends on cond, you can put it in a block:

if (cond) {
  val name = ...
  // do more here
}
0
source

All Articles