使用 XMLStarlet,我想在列表中添加另一个属性,
<document>
<properties>
<property>...</property>
<property>...</property> <!-- add this! -->
</properties>
</document>
这很容易,除了“properties”标签是可选的并且可能在原始文档中丢失,在这种情况下需要有条件地创建“properties”标签。
使用 XMLStarlet,我想在列表中添加另一个属性,
<document>
<properties>
<property>...</property>
<property>...</property> <!-- add this! -->
</properties>
</document>
这很容易,除了“properties”标签是可选的并且可能在原始文档中丢失,在这种情况下需要有条件地创建“properties”标签。
该ed
子命令没有任何条件,因此没有什么好方法,但我认为您可以插入一个新properties
元素,然后如果结果是“额外”(即不是第一个)则将其删除:
xmlstarlet ed \
-s /document -t elem -n properties -v '' \
-d '/document/properties[position() != 1]' \
-s /document/properties -t elem -n property -v 'new property value' \
doc.xml
否则,您可以先检查sel
并使用 shell 条件来决定是否需要插入。
在 Windows Batch 中,您可以执行 SEL 然后检查 %errorlevel% 0 表示已找到 1 表示未找到
例子:
xmlstarlet.exe -q sel -t -c "/config/option[@name='product']" xml.cfg
if %errorlevel%==1 (
xmlstarlet.exe ed -L -s "/config/" -t elem -n "option" -v "" -i "/config/option[last()]" -t attr -n "name" -v "product" xml.cfg
)
这是我批量使用的,你需要sed:
rem var may be set by following command
Set NodeCount=
rem count how many nodes, pipe to sed to put in the SET
xml sel -T -t -v "count(/document/properties)" -n doc.xml|sed "s/^/Set NodeCount=/" >tmp2.bat
Call tmp2.bat
Delete tmp2.bat
if "%NodeCount%"=="0" Goto NoNodes
rem Do Insert Node Here
Goto :eof
:NoNodes
rem handle no nodes Here
如果您找到更好的方法,我会全力以赴。