Construct XML with dynamic label and attributes in Scala?

前端 未结 2 749
走了就别回头了
走了就别回头了 2020-12-23 22:42

I want to be able to do this:

val myXml =  

(because I don\'t know what the attribute details

相关标签:
2条回答
  • 2020-12-23 23:22
    val myXml = <myTag/> % Attribute(None, "name", Text("value"), Null)
    

    See scala.xml.Attribute for different constructors.

    Adding the same attribute to all children:

    scala> val xml = <root><a/><b/><c/></root>
    xml: scala.xml.Elem = <root><a></a><b></b><c></c></root>
    
    scala> xml.child map (_ match {
         | case elem : Elem => elem % Attribute(None, "name", Text("value"), Null)
         | case x => x
         | })
    res3: Sequence[scala.xml.Node] = ArrayBuffer(<a name="value"></a>, <b name="value"></b>, <c name="value"></c>)
    

    You can also use the stuff in scala.xml.transform to do so recursively to all XML:

    val rr = new RewriteRule {
      override def transform(n: Node): Seq[Node] = n match {
        case elem : Elem => elem % Attribute(None, "name", Text("value"), Null) toSeq
        case other => other
      }
    }
    
    val rt = new RuleTransformer(rr)
    
    scala> rt(xml)
    res5: scala.xml.Node = <root name="value"><a name="value"></a><b name="value"></b><c name="value"></c></root>
    

    Or you can add attributes to arbitrary parts of the xml:

    scala> val xml = <root>{<a/> % Attribute(None, "name", Text("value"), Null)}</root>
    xml: scala.xml.Elem = <root><a name="value"></a></root>
    

    EDIT

    Changing the name is easy to do on Scala 2.8, like this:

    val someTag = "tag"
    val myXml = <root>{<a/>.copy(label = someTag)}</root>
    
    0 讨论(0)
  • 2020-12-23 23:33

    Note: you need to

    import scala.xml.Null
    

    to get this to work, and not scala.Null, which also exists.

    0 讨论(0)
提交回复
热议问题