xml - XSLT 删除空节点和带 -1 的节点

标签 xml xslt

我不是 XSLT 向导。

我有当前的 XSLT,我正在使用它来删除空节点:

 string strippingStylesheet = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" +
                "<xsl:template match=\"@*|node()\">" +
                "<xsl:if test=\". != ''\">" +
                "<xsl:copy>" + 
                "<xsl:apply-templates select=\"@*|node()\"/>" +
                "</xsl:copy>" + 
                "</xsl:if></xsl:template></xsl:stylesheet>";

我需要找到一种方法来删除其中包含 -1 的节点。以前的开发人员认为让系统中的每个 int 默认为 -1 是个好主意,是的,这意味着所有 DB 字段都包含 -1 而不是 null。

尽管我很想打败死马(用棍子、球棒、火箭筒),但我需要回去工作并完成这件事。

任何帮助都会很棒。

最佳答案

I have the current XSLT i'm using to remove empty nodes:

. . . . . . . . .

I need to find a way to also remove nodes with -1 in them

我猜想需要删除所有“空节点”。

处理取决于“空节点”的定义。在您的情况下,一个合理的定义是:任何没有属性和子元素或没有属性并且只有一个子元素是值为 -1 的文本节点的元素。 em>.

对于这个定义这里是一个简单的解决方案。

这个转换:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="*[not(@*) and not(*) and (not(text()) or .=-1)]"/>
</xsl:stylesheet>

应用于此示例 XML 文档时:

<t>
 <a>-1</a>
 <a>2</a>
 <b><c/></b>
 <d>-1</d>
 <d>15</d>
 <e x="1"/>
 <f>foo</f>
</t>

产生想要的、正确的结果:

<t>
   <a>2</a>
   <b/>
   <d>15</d>
   <e x="1"/>
   <f>foo</f>
</t>

关于xml - XSLT 删除空节点和带 -1 的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4404491/

相关文章:

xml - 没有元素引用的 XSD complexType 有什么用?

java - 在 GAE 上解析完全有效的 XML 时出现 "Content is not allowed in prolog"

xml - XSLT 中的词频计数器

xslt - 通过 XSLT 用 XHTML 中的标签替换 style= 属性

c# - 使用 XSL 将 XML 转换为 XAML

xml - 如何使用 XQuery 组合多个 XML 文件

快速计算大字符串之间距离的 C# 代码或算法?

c# - 如何在 C# 中对 XmlDocument 中的元素的子元素进行排序?

java - XSL 通过偏移比较将 UTC 时间转换为本地日期时间

xslt - 寻找(伪)XSLT 预处理器/模板器以使其不那么冗长