xmlscalaanti-xml

Replacing an XML node with Anti-XML


I am struggling to replace a XML element with another one using the library anti-xml. For instance, I have:

<root>
  <sub>
    <keep />
    <replace />
    <keeptoo />
  </sub>
</root>

and the fragment:

<inserted key="value">
  <foo>foo</foo>
  <bar>bar</bar>
</inserted>

I would like to produce:

<root>
  <sub>
    <keep />
    <inserted key="value">
      <foo>foo</foo>
      <bar>bar</bar>
    </inserted>      
    <keeptoo />
  </sub>
</root>

Note: The order of <sub> children must be conserved.


Solution

  • First we define the root document :

    val root = 
    <root>
      <sub>
        <keep />
        <replace />
        <keeptoo />
      </sub>
    </root>.convert
    
    val inserted =
      <inserted key="value">
        <foo>foo</foo>
        <bar>bar</bar>
     </inserted>.convert
    

    then we get the element :

    val replace = root \\ 'replace
    

    and finally we get the xml with updated <replace/> node :

    replace.updated(0, inserted).unselect
    

    if we get multiple <replace/> nodes, we will be able to iterate over replace to update each node.