如何用xmlstarlet为XML添加子元素并复制父元素值生成新元素?
解决xmlstarlet转换XML的问题
首先,你的命令没生效有两个关键原因:一是命令拼写错误(xmlstartlet应为xmlstarlet),二是原命令仅添加了空的<p>元素,未处理文本迁移和<subtitle>节点的创建。
以下是实现需求的完整命令:
xmlstarlet ed -L \ # 为<title>添加<p>子元素 -s //title -t elem -n p \ # 将<title>内的文本移动到<p>中 -m //title/text()[normalize-space()] -t move -i //title/p -t last \ # 在<xml>根节点下新增<subtitle>元素 -s //xml -t elem -n subtitle \ # 为<subtitle>添加<p>子元素 -s //subtitle -t elem -n p \ # 将<title>的文本内容赋值给<subtitle>下的<p> -v //subtitle/p -t set -x "//title/text()" \ $1
命令说明:
-L:直接原地修改目标XML文件-s:用于新增元素节点-m:移动节点(这里把标题文本移到<p>内部)-v:设置元素的文本内容,通过XPath//title/text()获取原标题文本
如果需要去除文本首尾的空格,可将最后一行的//title/text()替换为normalize-space(//title/text())。
执行后,XML会被转换为目标格式:
<xml> <title><p> Testing the tittle of the file </p></title> <subtitle><p> Testing the tittle of the file </p></subtitle> </xml>
内容的提问来源于stack exchange,提问作者Ofuuzo
相关产品推荐
相关产品推荐

