如何使用shell脚本更新xml中的值?

时间:2013-07-30 07:31:59

标签: shell unix awk

我有一个格式低于

的XML
<config>
        <global> 
                <log>
                        <file>log/global.log</file>
                        <level>DEBUG</level>
                </log>
        </global>
        <pipeline name="MediaExchange">
                <stop-file>MediaExchange.STOP</stop-file>
                <!--Delay in seconds before each poll-->
                <poll-delay>30</poll-delay>
                <source type="Cardinal-CH5-Meta">
                        <passive-mode>true</passive-mode>
                        <username>cardinalch5</username>                       
                </source>
            ....

我正在尝试在标签中打印该值,然后将其替换为其他值。我写下以下代码只打印标签中的值

# Retrieve value from XML file
xpath()
{
        log DEBUG $scriptFile "Parsing XML xpath"
        if [ `echo $1 | grep -v grep | grep /@ | wc -l` -ne 0 ]; then
                argDelta=`echo $1 | sed ' s!.*/@!! ; s/"$// '`
                value=`echo "cat $1" | xmllint --shell $2 | grep -v grep | grep = | sed -n 's|'${argDelta}'="\(.*\)"|\1|p'`
        else
                argDelta=`echo $1 | sed ' s!.*/!! ; s/"$// '`
                value=`echo "cat $1" | xmllint --shell $2 | sed -n 's|<'${argDelta}'>\(.*\)</'${argDelta}'>|\1|p'`
        fi
        echo $value
}
username=$(xpath /config/pipeline/[@name=\'MediaExchange\']/source/[@type=\'Cardinal-CH5-Meta\']/username config/config.xml)

我得到了以下异常

XPath error : Invalid expression
/config/pipeline/[@name='MediaExchange']/source/[@type='Cardinal-CH5-Meta']/username
                 ^
xmlXPathEval: evaluation failed
/config/pipeline/[@name='MediaExchange']/source/[@type='Cardinal-CH5-Meta']/username: no such node

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您的Xpath查询不正确,请查看:

/config/pipeline[@name='MediaExchange']/source[@type='Cardinal-CH5-Meta']/username/text()