用命名空间替换XSLT? [英] XSLT replacement with namespaces?
问题描述
如果我有一个带有命名空间的xml并希望应用某些值替换,那么我需要更改什么?
http://xslt.online-toolz.com/tools/xslt -transformation.php
If I have an xml with namespaces and want to apply some values replacement, what do I have to change? http://xslt.online-toolz.com/tools/xslt-transformation.php
<?xml version="1.0"?>
<accounts>
<account>
<name>Alex</name>
</account>
<account>
<name>Fiona</name>
</account>
</accounts>
这会将名称值更改为Johndoe:
This will change alle name values to "Johndoe":
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="account/name/text()">
<xsl:text>JohnDoe</xsl:text>
</xsl:template>
</xsl:stylesheet>
但是如果我在非常标记之前有一个名称空间,例如:
But what if I have a namespace before very tag, like:
<?xml version="1.0"?>
<my:accounts>
<my:account>
<my:name>Alex</my:name>
</my:account>
<my:account>
<my:name>Fiona</my:name>
</my:account>
</my:accounts>
推荐答案
两种方法。在样式表标记中包含'my'名称空间,如下所示:
Two ways of doing this. Either include the 'my' namespace in the stylesheet tag like this:
< xsl:stylesheet version =1.0xmlns:xsl = http://www.w3.org/1999/XSL/Transformxmlns:my =(insertnamespacehere)>
和执行
< xsl:template match =my:account / my:name / text()
>
或做得相当笨拙:
< xsl:template match = * [local-name()='account'] / * [local-name()='name'] / text()>
我倾向于阻止后一种方法 - 存在名称空间以区分具有相同本地名称的元素(例如 employee:name
和 company:name
例如),通过使用 local-name()
,您忽略了这种区别。换句话说,如果您的文档恰好包含 foo:account / foo:name
,您也会意外地替换它。
I'd be inclined to discourage the latter approach though- namespaces exist to distinguish between elements that have the same local name (such as employee:name
and company:name
for example), by using local-name()
you ignore that distinction. In other words, if your document happens to contains foo:account/foo:name
, you'll accidentally replace that too.
顺便提一下,您的上一个示例XML无效 - 未声明 my
命名空间。你的root my:accounts
需要包含这个< my:accounts xlmns:my =(insertnamespacehere)>
Incidentally, your last sample XML isn't valid- the my
namespace is not declared. Your root my:accounts
would need to include this with <my:accounts xlmns:my="(insertnamespacehere)">
这篇关于用命名空间替换XSLT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!