我有一段代码:
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>
一样添加它
答案 0 :(得分: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不在您期望的位置或其他地方,请不要犹豫。