XSLT命名空间理解



如果我删除所有名称空间和前缀,我的XSLT转换就可以完美地工作。

我曾尝试过几次引入名称空间,但最终总是出现某种错误或没有输出,所以在这里我寻求一些帮助和理解。

我的预期输出,缩减为名称空间和前缀,是:

<?xml version="1.0" encoding="utf-8"?>
<gpx xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="1.0" creator="GSAK"
xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0/1 http://www.groundspeak.com/cache/1/0/1/cache.xsd http://www.gsak.net/xmlv1/6 http://www.gsak.net/xmlv1/6/gsak.xsd"
xmlns="http://www.topografix.com/GPX/1/0">
<desc>...</desc>
<author>...</author>
<wpt lat="..." lon="...">
<name>...</name>
...
<gsak:wptExtension xmlns:gsak="http://www.gsak.net/xmlv1/6">
<gsak:DNF>...</gsak:DNF>
...
</gsak:wptExtension>
<groundspeak:cache id="..." available="..." archived="..." xmlns:groundspeak="http://www.groundspeak.com/cache/1/0/1">
<groundspeak:name>...</groundspeak:name>
</groundspeak:cache>
</wpt>
<wpt lat="..." lon="...">
...
</wpt>
</gpx>

XML输入再次精简为:

<AdventureModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/GamePlayer.Business.WebAPI.Contracts.Models">
<Message i:nil="..."/>
<DeepLink>..</DeepLink>
<Description>...</Description>
...
<GeocacheSummaries>
<GeocacheSummaryModel>
<Mode i:nil="..."/>
<Id>...</Id>
<Location>
<Altitude i:nil="..."/>
<Latitude>...</Latitude>
<Longitude>...</Longitude>
</Location>
...
</GeocacheSummaryModel>
<GeocacheSummaryModel>
...
</GeocacheSummaryModel>
</GeocacheSummaries>
...
</AdventureModel>

为了实现正确的命名空间转换,我需要向XSLT标头添加什么?

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
...
</xsl:stylesheet>

未指定XSLT版本。XSLT2.0/3.0使名称空间处理更加容易。

下面是它在XSLT1.0中的工作原理

输入XML有一个默认名称空间:

xmlns="http://schemas.datacontract.org/2004/07/GamePlayer.Business.WebAPI.Contracts.Models"

意思是:

  • 输入XML中的每个元素都绑定到它
  • XSLT需要用前缀指定默认名称空间。比方说"a">

因此XSLT如下所示:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:a="http://schemas.datacontract.org/2004/07/GamePlayer.Business.WebAPI.Contracts.Models">
<xsl:template match="/">
<xsl:value-of select="a:AdventureModel/a:DeepLink"/>
</xsl:template>
</xsl:stylesheet>

最新更新