Search code examples
xmlxmlstarlet

xmlstarlet how to update an attribute based on subelement value


<?xml version='1.0' encoding='UTF-8'?>
<star ABC="90" ABCType="Catch" endDateTime="2020-12-30T23:59:59" startDateTime="2010-08-10T06:00:00" timePeriodInDays="1" xmlns="urn:xxx:dyn:xxx:version01">    
    <tpName>seg</tpName>
    <Instance endDateTime="2016-06-08T00:01:00"   
              startDateTime="2016-06-08T00:01:00">  
        <Id>PASS1</Id>
    </Instance>
    <Instance endDateTime="2016-06-10T00:00:00"      
              startDateTime="2016-06- 08T00:01:00">
        <Id>PASS2"</Id>
    </Instance>
</star>

I am new to xmlstartlet. In the above code, I am trying to modify the startDateTime to "AAAA" of instance where Id is PASS1. I tried to do the below:

xml ed -N w=urn:xxx:dyn:xxx:version01 -u "/w:star/w:Instance[@w:startDateTime"]/@w:startDateTime" -v "AAAA" 1.xml 

but getting following error:

None of the XPaths matched; to match a node in the default namespace use '' as the prefix (see section 5.1 in the manual). For instance, use /:node instead of /node


Solution

  • You shouldn't need to prefix the attributes in your XPath.

    Try this:

    xml ed -N w=urn:xxx:dyn:xxx:version01 -u "/w:star/w:Instance[w:Id='PASS1']/@startDateTime" -v "AAAA" 1.xml 
    

    Output:

    <star xmlns="urn:xxx:dyn:xxx:version01" ABC="90" ABCType="Catch" endDateTime="2020-12-30T23:59:59" startDateTime="2010-08-10T06:00:00" timePeriodInDays=
    "1">
      <tpName>seg</tpName>
      <Instance endDateTime="2016-06-08T00:01:00" startDateTime="AAAA">
        <Id>PASS1</Id>
      </Instance>
      <Instance endDateTime="2016-06-10T00:00:00" startDateTime="2016-06- 08T00:01:00">
        <Id>PASS2"</Id>
      </Instance>
    </star>