简体   繁体   中英

Patching bean config XML file dynamically using sed?

I have a bean configuration XML file which looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>MyDriver</value>
        </property>
        <property name="url">
            <value>#####</value>
        </property>
        <property name="username">
            <value>myUser</value>
        </property>
        <property name="password">
            <value>myPassword</value>
        </property>
    </bean>
</beans>

I want to replace the string ##### dynamically with sed.

##### may have different values, eg myUrl1 , myUrl2 etc. and should be replaced with another given myUrlX

So the result should be something like:

        ...
        <property name="url">
            <value>myUrlX</value>
        </property>
        ...

So far I only got close to a solution with the following sed command:

sed -n "1h;1!H;${;g;s|\(<property [^>]*>.*<value>\).*\(</value>.*</property>\)|\1myUrl\2|g;p;}" test.xml

But this replaces the myPassword string in my XML file instead of ##### .

Could anyone give me a hint what I need to change in my sed command?

Thanks a lot!

Use xmlstarlet :

xml ed --update "/beans/bean[@id='myDataSource']/property[@name='url']/value" --value myUrlX inputfile.xml

To query:

xml sel -t -m "/beans/bean[@id='myDataSource']/property[@name='url']" -v value inputfile.xml

Put them together:

#!/bin/bash
file=inputfile.xml
val=$(xml sel -t -m "/beans/bean[@id='myDataSource']/property[@name='url']" -v value "$file")
if [[ $val == "foo" ]]
then
    val=bar
    xml ed --update "/beans/bean[@id='myDataSource']/property[@name='url']/value" --value "$val" "$file"
fi

On my system, the command is xmlstarlet instead of xml .

Don't use regexes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM