转换 XML 以将“nil"属性添加到空元素 [英] Transform XML to add 'nil' attributes to empty elements

查看:26
本文介绍了转换 XML 以将“nil"属性添加到空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用的现有 XML 提要有很多属性,它们的值可能会丢失,我们希望将这些属性视为 NULL 而非可选值或空值,因为这会使强制执行严格的类型变得更加困难,并且会扰乱我们的自动代码生成等等.

An existing XML feed we consume has a lot of properties whose values can be missing, and we want to treat these as NULL not optional or empty values because it makes enforcing strict typing harder and messes up our auto code generation and so on.

例如,我们可能会收到:

For instance we might receive: <LASTUPDATED/>

我们没有正式的 XSD,但正在自己创建一个...它目前看起来像:<xs:element type="xs:dateTime" name="LASTUPDATED"/>

We have no formal XSD but are creating one ourselves... it might currently look like: <xs:element type="xs:dateTime" name="LASTUPDATED"/>

这不会根据显示的 XML 进行验证("" 不是有效的 dateTime).理想情况下,它会在 XML 中有 xsi:nil=true (nillable 和 minOccurs XSD 元素属性)

This doesn't validate against the XML shown ("" is not a valid dateTime). Ideally it would instead have xsi:nil=true in the XML (nillable and minOccurs XSD element attributes)

由于我们不控制提要,我可以创建一个转换,将任何 <xxx/> 元素替换为 <myElement xsi:nil='true'/>?将我们的 XSD 改为使用 minOccurs 并不是很好,因为那样我们必须检查每个元素是否存在,而不仅仅是支持 NULL 值.

Since we don't control the feed, can I create a transform that will replace any <xxx/> element with <myElement xsi:nil='true'/>? Instead changing our XSD to use minOccurs is not great because then we have to check if each element exists or not rather than just supporting NULL values.

推荐答案

以下应该有效.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <xsl:output method="xml" indent="yes"/>

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

    <xsl:template match="*[not(text())]">
        <xsl:copy>
            <xsl:attribute name="xsi:nil">true</xsl:attribute>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

然而,这也将匹配 <LASTUPDATED></LASTUPDATED>,它在语义上与

This however, will also match <LASTUPDATED></LASTUPDATED> which is semantically identical to <LASTUPDATED />

这篇关于转换 XML 以将“nil"属性添加到空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆