我不确定是否完全理解它的孩子不存在 ......或者我添加它的确切含义,但这是我选择添加书籍的直接孩子的直接答案:
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 不在您预期的地方或其他地方时,请不要犹豫。