Find and Replace and attribute in XML file using libxml/xpath in C program

206 Views Asked by At

I have a xml file which has different sections and i need to 'rename' certain attributes appearing in this huge file (like find and replace with new name). All over i have used libxml and xpath to modify and satisfy other requirements, but for this one, i am not sure how this can done using libxml and xpath APIs. Please help.

e.g In the below file i need to find all 'ORANGE' string and replace it with say 'PURPLE' string. Please help..

<a>
    <my_section enum="ORANGE" name="blah"> </my_section> 
    <my_section enum="APPLE" name="blah blah"> </my_section>
    <my_section enum="ORANGE1" name="blah1"> </my_section>
    <your_section color="ORANGE" name="blah"> </your_section> 
    <another_section city="LONDON" blah="ORANGE"> </another_section>
    <any_section code="RED" age="ORANGE"> </any_section> 
</a>
1

There are 1 best solutions below

6
Davey van Tilburg On

I know XPath and how complicated it can be... but, maybe the solution to this problem is just a simple string replace? But maybe there are scenarios that I am not thinking of that you are not showing here this does not match for.

But if you really want to do it through xpath

//*[@*='ORANGE']

Selects all elements that contain an attribute with value orange

//*[@*='ORANGE']/@*[string()='ORANGE']

Gets you only the attributes