Dha*_*lan 2 xml linux xslt awk gawk
我正在尝试使用AWK脚本根据条件对xml文件进行更新.有人可以帮我吗?
students.xml
<students>
<student>
<stuId>1</stuId>
<name>A</name>
<mark>75</mark>
<result></result>
</student>
<student>
<stuId>2</stuId>
<name>B</name>
<mark>35</mark>
<result></result>
</student>
<student>
<stuId>1</stuId>
<name>C</name>
<mark>94</mark>
<result></result>
</student>
</students>
Run Code Online (Sandbox Code Playgroud)
我到目前为止尝试的代码
我可以使用下面的代码提取标签值
BEGIN { RS="<[^>]+>" }
{ print RT, $0 }
Run Code Online (Sandbox Code Playgroud)
这将按预期打印所有标记和值.
我想更新<result>标记为通过,如果标记> 40别的失败
产量
<students>
<student>
<stuId>1</stuId>
<name>A</name>
<mark>75</mark>
<result>pass</result>
</student>
<student>
<stuId>2</stuId>
<name>B</name>
<mark>35</mark>
<result>fail</result>
</student>
<student>
<stuId>1</stuId>
<name>C</name>
<mark>94</mark>
<result>pass</result>
</student>
</students>
Run Code Online (Sandbox Code Playgroud)
有人能协助我吗?
另一种选择是使用ed(编辑)命令的xmlstarlet ...
xmlstarlet ed -L -u "//student[mark >= 40]/result" -v "pass" -u "//student[40 > mark]/result" -v "fail" students.xml
Run Code Online (Sandbox Code Playgroud)
注意:该-L命令行会编辑文件就地.如果这不是您想要的行为,请务必将其删除.
您还可以将XSLT 1.0与xmlstartlet一起使用(tr(转换)命令)...
update.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="student[mark >= 40]/result">
<xsl:copy>pass</xsl:copy>
</xsl:template>
<xsl:template match="student[40 > mark]/result">
<xsl:copy>fail</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
命令行
xmlstarlet tr update.xsl students.xml
Run Code Online (Sandbox Code Playgroud)