开发者

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, e.g. 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 myPassw开发者_StackOverflow社区ord 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜