paradigmatic
paradigmatic

Reputation: 40461

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.

Upvotes: 4

Views: 629

Answers (2)

ncreep
ncreep

Reputation: 497

You can replace selected elements with several nodes using flatMap, e.g. replace.flatMap(_ => someListOfNodes).unselect

(Sorry for making it a separate answer, it appears that I can't comment on existing ones.)

Upvotes: 2

David
David

Reputation: 2399

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.

Upvotes: 3

Related Questions