Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
863 views
in Technique[技术] by (71.8m points)

scala - XML insert/update

do you know any Scala API to insert and (or) update Nodes according to XPath? e.g for a given Node and XPath, this API would create a copy of XML with new node

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the RewriteRule to do this, 2.10.3 documentation.

val cats = <Cats>
  <Cat Name="Floyd"/>
  <Cat Name="Onyx"/>
</Cats>

Then suppose the RewriteRule

class AddCat(name: String) extends RewriteRule {
   override def transform(n: Node): Seq[Node] = n match {
     case e: Elem if e.label == "Cats" =>
       val cats = (e \ "Cat")
       val newCat = <Cat Name={name}/>
       new Elem(e.prefix, "Cats", e.attributes, e.scope, e.minimizeEmpty, (cats ++ newCat).toSeq:_*)
     case x => x
   }
 }

Then you could do,

val rule = new RuleTransformer(new AddCat("Stevie"))
rule.transform(cats)
res2: Seq[scala.xml.Node] = List(<Cats><Cat Name="Floyd"/><Cat Name="Onyx"/><Cat Name="Stevie"/></Cats>)

Similarly if you wanted to change an attribute

class AddLastName(name: String, lastName: String) extends RewriteRule {
  override def transform(n: Node): Seq[Node] = n match {
    case e: Elem if e.label == "Cat" && (e \ "@Name" text).equals(name) =>
      val cat: String = e.attributes("Name").head.text
      e % Attribute(None, "Name", Text(s"$name $lastName"), Null)
    case x => x
  }
}

val rule = new RuleTransformer(new AddLastName("Stevie", "Nicks"))
rule.transform(cats)
res3: Seq[scala.xml.Node] = List(<Cats><Cat Name="Floyd"/><Cat Name="Onyx"/><Cat Name="Stevie Nicks"/></Cats>)

Both of these approaches would do what you're looking for. The hard part is figuring out how to get at the children, then build the parent node.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...