4

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.

paradigmatic
  • 40,153
  • 18
  • 88
  • 147

2 Answers2

3

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.

David
  • 2,399
  • 20
  • 17
  • Thanks for your answer. Any idea how I can replace the `` element by a list of several nodes ? – paradigmatic Nov 21 '11 at 09:36
  • I'm not sure that it's possible but I'm not an antixml expert. Could you consider to have ``, `` ... and to replace them individually ? – David Nov 21 '11 at 11:14
  • No, because I don't know in advance how many nodes I should add. I use another approach now, but I will fill another question about it, if I meet the problem again. – paradigmatic Dec 07 '11 at 07:55
2

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.)

ncreep
  • 473
  • 3
  • 11