2

我有代码块:

object XmlExample {

  def main(args: Array[String]): Unit = {
    val someXml = 
     <books>
      <book title="The Woman in White">
        <author>Wilkie Collins</author>
      </book> <book title="Great Expectations">
        <author>Charles Dickens</author>
      </book>
    </books>
    println("The xml object is of type: " + someXml.child)


  }

}

我想检查节点<c1>是否不存在作为它的子节点,然后我添加它就像<c1>Null</c1>

4

1 回答 1

1

我不确定是否完全理解它的孩子不存在 ......或者我添加它的确切含义,但这是我选择添加书籍的直接孩子的直接答案:

def addC1IfNotHere(someXml: scala.xml.Elem) = (someXml \ "c1") match {
  case Seq() =>
    someXml.copy(child = <c1>Null</c1> +: someXml.child)
  case _ => someXml
}

这就像:

val someXmlWithC1 = 
<books>
   <c1>anything else</c1>
   <book title="The Woman in White">
    <author>Wilkie Collins</author>
   </book> <book title="Great Expectations">
    <author>Charles Dickens</author>
  </book>
</books>
val someXmlWithoutC1 = 
<books>
   <book title="The Woman in White">
    <author>Wilkie Collins</author>
   </book> <book title="Great Expectations">
    <author>Charles Dickens</author>
  </book>
</books>
val hasItsOriginalC1 = addC1IfNotHere(someXmlWithC1)
val hasANewC1 = addC1IfNotHere(someXmlWithoutC1)
println(hasItsOriginalC1)
println(hasANewC1)

通常应该打印:

<books>
   <c1>anything else</c1>
   <book title="The Woman in White">
    <author>Wilkie Collins</author>
   </book> <book title="Great Expectations">
    <author>Charles Dickens</author>
  </book>
</books>
<books><c1>Null</c1>
   <book title="The Woman in White">
    <author>Wilkie Collins</author>
   </book> <book title="Great Expectations">
    <author>Charles Dickens</author>
  </book>
</books>

希望能帮助到你。每当 c1 不在您预期的地方或其他地方时,请不要犹豫。

于 2019-03-22T16:10:00.603 回答