xmlbashsed

sed command in bash to add XML content from one file to another


I have below file1.xml:

<loginIpRanges>
    <description>undefined</description>
    <endAddress>1.2.3.4</endAddress>
    <startAddress>1.2.3.0</startAddress>
</loginIpRanges>

I have below file2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
    <applicationVisibilities>
        <application>standard__S</application>
        <default>false</default>
        <visible>false</visible>
    </applicationVisibilities>
    <custom>true</custom>
    <userPermissions>
        <enabled>true</enabled>
        <name>ViewRoles</name>
    </userPermissions>
</Profile> 

I want to append all content of file1.xml to file2.xml but after custom tag and before userPermissions tag:

<?xml version="1.0" encoding="UTF-8"?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
    <applicationVisibilities>
        <application>standard__S</application>
        <default>false</default>
        <visible>false</visible>
    </applicationVisibilities>
    <custom>true</custom>
    <loginIpRanges>
        <description>undefined</description>
        <endAddress>1.2.3.4</endAddress>
        <startAddress>1.2.3.0</startAddress>
    </loginIpRanges>
    <userPermissions>
        <enabled>true</enabled>
        <name>ViewRoles</name>
    </userPermissions>
</Profile> 

I need this solution added to Azure build pipeline in bash script. Already tried 'sed' command and I couldn't find this solution. Please can I get some help!!


Solution

  • sed and other text processors are not the right tool to manipulate structured data such as XML. Use a processor that knows about how data can (and must) be structured within XML-encoded documents.

    xmlstarlet and xmllint have already been suggested, here's an approach using xq which comes with kislyuk/yq:

    xq -x --xml-dtd '.Profile |= with_entries(
      select(.key != "custom") // (., (input | to_entries[]))
    )' file2.xml file1.xml
    
    <?xml version="1.0" encoding="utf-8"?>
    <Profile xmlns="http://soap.sforce.com/2006/04/metadata">
      <applicationVisibilities>
        <application>standard__S</application>
        <default>false</default>
        <visible>false</visible>
      </applicationVisibilities>
      <custom>true</custom>
      <loginIpRanges>
        <description>undefined</description>
        <endAddress>1.2.3.4</endAddress>
        <startAddress>1.2.3.0</startAddress>
      </loginIpRanges>
      <userPermissions>
        <enabled>true</enabled>
        <name>ViewRoles</name>
      </userPermissions>
    </Profile>