开发者

Replace attribute value with unknown namespace using XSLT

I have an XML from customer where I cannot be certain of the namespace. I need to replace value of some attribute. Here is the input XML example:

<?xml version="1.0" encoding="UTF-8"?>
<NetworkSection xmlns:ovf="http://com/deployment/1.0">
    <Network ovf:name="bridged"/>
</NetworkSection>

I want to receive the XML like this:

<?xml version="1.0" encoding="UTF-8"?>
<NetworkSection xmlns:ovf="http://com/deployment/1.0">
    <Network ovf:name="VM network"/>
</NetworkSection>

Here the XSL I try to use:

开发者_运维百科
<?xml version="1.0" encoding="utf-8"?>
  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="utf-8"/>
  <xsl:template match="NetworkSection/Network/@*[local-name()='name']">
    <xsl:attribute name='name'>VM Network</xsl:attribute>
  </xsl:template>

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

The problem is that I lose the attribute namespace. I cannot define namespace in my XSL, because it may vary in different input XMLs, I just want to change the attribute value.

Is it possible to do such replacing without specifying namespace in XSL? Thanks in advance.


This can be achieved by use of the name() and namespace-uri() functions.

<xsl:attribute name="{name()}" namespace="{namespace-uri()}">VM Network</xsl:attribute>

When you use this line in your XSLT, you should get the output you desire

<Network ovf:name="VM network"/> 


My preferred approach to this problem is a two pass solution: first normalize the namespaces, then do your "real" processing. The benefit of this is that the normalization step in the pipeline can be reused whatever the subsequent processing your want to do, and it will always make the subsequent processing easier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜