How to change attribute on Scala XML Element

后端 未结 5 797
渐次进展
渐次进展 2020-12-13 04:41

I have an XML file that I would like to map some attributes of in with a script. For example:


  
         


        
5条回答
  •  不知归路
    2020-12-13 05:17

    I found it easier to create a separate XML snippet and merge. This code fragment also demonstrates removing elements, adding extra elements and using variables in an XML literal:

    val alt = orig.copy(
      child = orig.child.flatMap {
        case b: Elem if b.label == "b" =>
          val attr2Value = "100"
          val x =   //////////////////// Snippet
          Some(b.copy(attributes = b.attributes.append(x.attributes)))
    
        // Will remove any  elems
        case removeMe: Elem if isElem(removeMe, "remove-me", "some-attrib" -> "specific value") => 
          None
    
        case keep => Some(keep)
      }
        ++
          
    
    // Tests whether the given element has the given label
    private def isElem(elem: Elem, desiredLabel: String, attribValue: (String, String)): Boolean = {
      elem.label == desiredLabel && elem.attribute(attribValue._1).exists(_.text == attribValue._2)
    }
    

    For other new-comers to Scala XML, you'll also need to add a separate Scala module to use XML in scala code.

提交回复
热议问题