我们想从XML
中删除CommentLine的空标签<CommentLine/>
INPUT XML:
<?xml version="1.0" encoding="WINDOWS-1252"?>
<SalesOrders xsd:noNamespaceSchemaLocation="SDOC.XSD" xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance">
<Orders>
<OrderHeader>
<CustomerPoNumber>AB-54354</CustomerPoNumber>
</OrderHeader>
<OrderDetails>
<CommentLine>
<Comment>Ensure saddle is color coded</Comment>
<OrderLineID>OR-1810127</OrderLineID>
</CommentLine>
<CommentLine>
<Comment>EDI-001</Comment>
<OrderLineID>OR-1810128</OrderLineID>
</CommentLine>
<StockLine>
<CustomerPoLine>9999</CustomerPoLine>
<StockCode>ABSH-SMH-12OZ-01</StockCode>
<StockDescription>SMH ABS BALANCE SHAMPOO 12OZ</StockDescription>
<OrderQty>1.0</OrderQty>
</StockLine>
<CommentLine>
<Comment>This is for test purpose</Comment>
<OrderLineID>OR-1810124</OrderLineID>
</CommentLine>
<CommentLine>
<Comment>EDI-SAVE</Comment>
<OrderLineID>OR-1810125</OrderLineID>
</CommentLine>
<CommentLine/>
</OrderDetails>
</Orders>
</SalesOrders>
尝试使用XML:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="Windows-1252" indent="yes"/>
<xsl:template match="@xsi:nil[.='true']" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<xsl:template match="@*|node()">
<xsl:copy copy-namespaces="no">
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
预期输出
<?xml version="1.0" encoding="WINDOWS-1252"?> -<SalesOrders xsd:noNamespaceSchemaLocation="SDOC.XSD" xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance">
-<Orders>
-<OrderHeader>
<CustomerPoNumber>AB-54354</CustomerPoNumber>
</OrderHeader>
-<OrderDetails>
-<CommentLine> <Comment>Ensure saddle is color coded</Comment>
<OrderLineID>OR-1810127</OrderLineID>
</CommentLine>
-<CommentLine> <Comment>EDI-001</Comment>
<OrderLineID>OR-1810128</OrderLineID>
</CommentLine>
-<StockLine>
<CustomerPoLine>9999</CustomerPoLine>
<StockCode>ABSH-SMH-12OZ-01</StockCode>
<StockDescription>SMH ABS BALANCE SHAMPOO 12OZ</StockDescription>
<OrderQty>1.0</OrderQty> </StockLine>
-<CommentLine> <Comment>This is for test purpose</Comment>
<OrderLineID>OR-1810124</OrderLineID>
</CommentLine>
-<CommentLine>
<Comment>EDI-SAVE</Comment>
<OrderLineID>OR-1810125</OrderLineID>
</CommentLine>
</OrderDetails>
</Orders>
</SalesOrders>
我们必须删除完整输入XML中的元素。
任何帮助将不胜感激!感谢宝贵的时间。
答案 0 :(得分:1)
此解决方案将移除所有空元素而不删除其父元素(即,如果您在结果集中获得了<OrderDetails><CommentLine/></OrderDetails>
并且空OrderDetails
元素。
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="Windows-1252" indent="yes"/>
<xsl:template match="@*|node()[./node()]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
即。我告诉系统只返回有子节点的节点(无论是元素还是文本)。
<xsl:template match="@*|node()[./node()]">
演示:http://xsltransform.net/jyRYYjs
Per @ Filburt的评论,如果你想删除一旦删除空子元素后变为空的元素,请按照以下链接提示: