0

I need to modify the parameters of a function in xml file with ElementTree while the elements have similar names. In this example I want to change only the number 2 and keep the others. Is it possible?

<Model>
    <Function>
      <param>x</param>
      <param>type</param>
      <param>2</param>
      <param>5</param>
     </Function>
</Model>
Elena Popa
  • 317
  • 3
  • 8
  • you can use xpath to select the correct `param`-element based on the value `2` (see [here](https://stackoverflow.com/questions/1198253/xpath-how-to-select-elements-based-on-their-value)). alternatively you could also select the third occurrence of `param` (see [here](https://stackoverflow.com/questions/4007413/xpath-query-to-get-nth-instance-of-an-element)). once you have the element, use `ElementTree`s capabilities to change the text (see [here](https://stackoverflow.com/questions/40244271/change-xml-element-text-using-xml-etree-elementtree)). – sim Feb 21 '20 at 14:43

1 Answers1

0

Just one example, though a little late.

from simplified_scrapy import SimplifiedDoc, utils, req
html = '''
<Model>
    <Function>
      <param>x</param>
      <param>type</param>
      <param>2</param>
      <param>5</param>
     </Function>
</Model>
'''
doc = SimplifiedDoc(html)
# Use text 2
param = doc.getElementByText('2',tag='param')
# Use index
param = doc.selects('param')[2]
param.setContent('Modified')
print(doc.html)

Result:

<Model>
    <Function>
      <param>x</param>
      <param>type</param>
      <param>Modified</param>
      <param>5</param>
     </Function>
</Model>
dabingsou
  • 2,469
  • 1
  • 5
  • 8