Search code examples
xmlxml-parsingxmlstarlet

XML Starlet Modify command for complex XML


I have an XML file that contains users identity information. I want to automate the modification and deletion of users and so far successful with deletion using XmlStarlet. Now i don't know how to modify a users information by searching it via username. Can anybody help me with the command how to modify using xmlstarlet

    <table name="MANAGED_USER" keys="CONTEXT_ID,USERNAME">
     <row>
     <column name="USERNAME">IAM_User7</column>
     <column name="CONTEXT_ID">PROVCLIENT</column>
     <column name="ALGORITHM">DESEDE</column>
     <column name="PASSWORD">2e02f952e8743b36</column>
     <column name="FAILED_LOGINS">0</column>
     <column name="REALNAME">IAM User 7</column>
     <column name="VALIDFROM">2013-06-03 00:00:00.0</column>
     <column name="VALIDUNTIL">2014-06-01 00:00:00.0</column>
     <column name="USER_TYPE">1</column>
     <column name="LOCKED">0</column>
     <column name="CHANGED_BY">tam</column>
     <column name="ORGANISATION_NAME" is_null="true">null</column>
    </row>
    </table>

Thanks in advance


Solution

  • Something like this? (lock the user with username "IAM_User7")

    xmlstarlet ed -u '/table/row[column[@name = "USERNAME"] = "IAM_User7"]/column[@name = "LOCKED"]' -v 1 table.xml
    

    Assuming table.xml contains the content in the question.


    To add a new user is unfortunately quite tedious, This is just the first 2 fields:

    xmlstarlet ed -s /table -t elem -n row -v '' \
        --var new '$prev' \
        -s '$new' -t elem -n column -v IAM_User8 \
        -s '$prev' -t attr -n name -v USERNAME \
        -s '$new' -t elem -n column -v PROVCLIENT \
        -s '$prev' -t attr -n name -v CONTEXT_ID \
        table.xml
    

    Requires version 1.4.0 or higher (for --var and $prev; it's possible to use earlier versions with ugly tricks).