VRV*_*ara 17 unix bash shell shell-script bash-scripting
我需要使用 unix 脚本或命令执行此操作 /home/user/app/xmlfiles 中有一个 xml 文件,例如
<book>
<fiction type='a'>
<author type=''></author>
</fiction>
<fiction type='b'>
<author type=''></author>
</fiction>
<Romance>
<author type=''></author>
</Romance>
</book>
Run Code Online (Sandbox Code Playgroud)
我想将小说中的作者类型编辑为 local 。
<fiction>
<author type='Local'></author>
</fiction>
Run Code Online (Sandbox Code Playgroud)
我需要单独使用属性 b更改小说标签中的作者类型。请使用 unix shell 脚本或命令帮助我解决这个问题。谢谢 !
cha*_*aos 26
如果您只想替换<author type=''><\/author>
为<author type='Local'><\/author>
,则可以使用该sed
命令:
sed "/<fiction type='a'>/,/<\/fiction>/ s/<author type=''><\/author>/<author type='Local'><\/author>/g;" file
Run Code Online (Sandbox Code Playgroud)
但是,在处理 xml 时,我推荐使用xmlstarlet 之类的 xml 解析器/编辑器:
$ xmlstarlet ed -u /book/*/author[@type]/@type -v "Local" file
<?xml version="1.0"?>
<book>
<fiction>
<author type="Local"/>
</fiction>
<Romance>
<author type="Local"/>
</Romance>
</book>
Run Code Online (Sandbox Code Playgroud)
使用该-L
标志内联编辑文件,而不是打印更改。
Kit*_*Kit 10
xmlstarlet edit --update "/book/fiction[@type='b']/author/@type" --value "Local" book.xml
Run Code Online (Sandbox Code Playgroud)
我们可以使用 xsl 文档doThis.xsl
并将source.xml
with 处理xsltproc
为newFile.xml
.
xsl 基于此问题的答案。
把这个放到一个doThis.xsl
文件中
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="no"/>
<!-- Copy the entire document -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- Copy a specific element -->
<xsl:template match="/book/fiction[@type='b']/author">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<!-- Do something with selected element -->
<xsl:attribute name="type">Local</xsl:attribute>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
现在我们生产 newFile.xml
$: xsltproc -o ./newFile.xml ./doThis.xsl ./source.xml
Run Code Online (Sandbox Code Playgroud)
这将是 newFile.xml
<?xml version="1.0" encoding="UTF-8"?>
<book>
<fiction type="a">
<author type=""/>
</fiction>
<fiction type="b">
<author type="Local"/>
</fiction>
<Romance>
<author type=""/>
</Romance>
</book>
Run Code Online (Sandbox Code Playgroud)
用于查找类型 b 小说的表达式是XPath
。
归档时间: |
|
查看次数: |
70872 次 |
最近记录: |