我将以下XML数据输入到我的XSLT中:
v=$(cat <file_path>)
echo $v
我想传递别名名称与“ M”匹配的<?xml version="1.0" encoding="UTF-8"?>
<Application>
<Data>
<Data1>
<name>Michale</name>
<age>65</age>
<Info>
<Alias name="M">
<Contactmail>abc@gmail.com</Contactmail>
<ContactPh>8988900009</ContactPh>
</Alias>
<Alias name="Q">
<Contactmail>abc@gmail.com</Contactmail>
<ContactPh>8988900009</ContactPh>
</Alias>
</Info>
</Data1>
<Data1>
<name>Albert</name>
<age>69</age>
<Info>
<Alias name="A">
<Contactmail>xyz@gmail.com</Contactmail>
<ContactPh>89889908709</ContactPh>
</Alias>
<Alias name="P">
<Contactmail>pqr@gmail.com</Contactmail>
<ContactPh>8988988779</ContactPh>
</Alias>
</Info>
</Data1>
</Data>
</Application>
块,即:
Data1
我对如何访问测试条件内的循环(即别名)感到困惑? 有没有更好的方法来执行此xslt?
<Application>
<Data>
<Data1>
<name>Michale</name>
<age>65</age>
<Info>
<Alias name=M>
<Contactmail>abc@gmail.com</Contactmail>
<ContactPh>8988900009</ContactPh>
</Alias>
<Alias name=Q>
<Contactmail>abc@gmail.com</Contactmail>
<ContactPh>8988900009</ContactPh>
</Alias>
</Info>
</Data1>
</Data>
</Application>
答案 0 :(得分:2)
以下模板将完成此工作。解释在代码中。
<?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" indent="yes"/>
<xsl:strip-space elements="*" /> <!-- Removes unnecessary space between elements -->
<!-- identity template --> <!-- Copies all nodes not matched by other templates -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="Data1[Info/Alias/@name != 'M']" /> <!-- Ignores all Data1 elements which don't have an @name='M' attribute child -->
<xsl:template match="Data1[Info/Alias/@name = 'M']"> <!-- Matches all Data1 elements which have the desired child attribute -->
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
其输出为:
<?xml version="1.0"?>
<Application>
<Data>
<Data1>
<name>Michale</name>
<age>65</age>
<Info>
<Alias name="M">
<Contactmail>abc@gmail.com</Contactmail>
<ContactPh>8988900009</ContactPh>
</Alias>
<Alias name="Q">
<Contactmail>abc@gmail.com</Contactmail>
<ContactPh>8988900009</ContactPh>
</Alias>
</Info>
</Data1>
</Data>
</Application>
答案 1 :(得分:-1)
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Application">
<xsl:copy>
<xsl:for-each select="Data/Data1">
<xsl:if test="Info/Alias[@name='M']">
<Data>
<Data1>
<xsl:apply-templates/>
</Data1>
</Data>
</xsl:if>
</xsl:for-each>
</xsl:copy>
</xsl:template>
You may also do like this