Search code examples
xmlxmllint

Modifying in line attribute in XML using xmllint


I'm trying to update the value of a field in a specific block but that value is in a wrapped attribute (not sure what the proper name should be), ie: <target_tag name="my_tag" default="value_to_update"/> rather than: <target_tag name="my_tag">value_to_update</target_tag>

I've been searching how to this and it seems to be something like:

xmllint --shell my_file.xml << EOF
cd //target_tag[@name="my_tag"]/default
set new_value
save
EOF

but this would work if the XML was of the second kind. How can I access/update the wrapped attribute? I can't seem to find the answer...


Solution

  • You were close!
    The cd shell command must refer to the @default attribute

    xmllint --shell tmp.xml << EOF
    cd //target_tag[@name="my_tag"]/@default
    cat .
    set new_value
    save
    bye
    EOF
    
    cat tmp.xml
    

    Console output

    / > cd //target_tag[@name="my_tag"]/@default
    default > cat .
     -------
     default="value_to_update"
    default > set new_value
    default > save
    default > bye
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        <target_tag name="my_tag" default="new_value"/>
    </root>
    

    xmllint version

    xmllint --version
    xmllint: using libxml version 20914