我有一个类似的问题:我有一个 Tomcat 配置文件 (server.xml),并且必须在<Resource>
该部分中插入一个具有预定义属性的标签<GlobalNamingResources>
。
这是它以前的样子:
<GlobalNamingResources>
<!-- Editable user database that can also be used
by UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase"
auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
这是我想要实现的目标:
<GlobalNamingResources>
<!-- Editable user database that can also be used
by UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase"
auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
<Resource name="jdbc/templateassets"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://DBHOST:DBPORT/DBNAME?createDatabaseIfNotExist=false&useUnicode=true&characterEncoding=utf-8"
username="DBUSER"
password="DBPASS"
maxActive="150"
maxIdle="10"
initialSize="10"
validationQuery="SELECT 1"
testOnBorrow="true" />
</GlobalNamingResources>
这是我的做法(来自 shell 脚本的片段):
if [ -n "$(xmlstarlet sel -T -t -v "/Server/GlobalNamingResources/Resource[@name='jdbc/templateassets']/@name" server.xml)" ]; then
echo "Resource jdbc/templateassets already defined in server.xml"
else
echo "Adding resource jdbc/templateassets to <GlobalNamingResources> in server.xml"
xmlstarlet ed -P -S -L -s /Server/GlobalNamingResources -t elem -n ResourceTMP -v "" \
-i //ResourceTMP -t attr -n "name" -v "jdbc/templateassets" \
-i //ResourceTMP -t attr -n "auth" -v "Container" \
-i //ResourceTMP -t attr -n "type" -v "javax.sql.DataSource" \
-i //ResourceTMP -t attr -n "driverClassName" -v "com.mysql.jdbc.Driver" \
-i //ResourceTMP -t attr -n "url" -v "jdbc:mysql://DBHOST:DBPORT/DBNAME?createDatabaseIfNotExist=false&useUnicode=true&characterEncoding=utf-8" \
-i //ResourceTMP -t attr -n "username" -v "DBUSER" \
-i //ResourceTMP -t attr -n "password" -v "DBPASS" \
-i //ResourceTMP -t attr -n "maxActive" -v "150" \
-i //ResourceTMP -t attr -n "maxIdle" -v "10" \
-i //ResourceTMP -t attr -n "initialSize" -v "10" \
-i //ResourceTMP -t attr -n "validationQuery" -v "SELECT 1" \
-i //ResourceTMP -t attr -n "testOnBorrow" -v "true" \
-r //ResourceTMP -v Resource \
server.xml
fi
诀窍是暂时给新元素一个唯一的名称,以便以后可以使用 XPATH 表达式找到它。添加所有属性后,名称将更改回 Resource(使用 -r)。
其他 xmlstarlet 选项的含义:
-P (or --pf) - preserve original formatting
-S (or --ps) - preserve non-significant spaces
-L (or --inplace) - edit file inplace