为什么 xsl:value-of 在这里不起作用(XML 命名空间)?
Why is xsl:value-of not working here (XML namespaces)?
我从 ASP.NET 网络 API 中获得了 XML 的以下片段:
<DrilldownModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/MY.API.Models">
<AddressInfo xmlns:d2p1="http://schemas.datacontract.org/2004/07/MY.API.Entities.Drilldown">
<d2p1:AddressNumber>4213</d2p1:AddressNumber>
<d2p1:AddressUseType>RESIDENTIAL</d2p1:AddressUseType>
<d2p1:EncryptedParcelId i:nil="true" />
<d2p1:GisError i:nil="true" />
<d2p1:GisErrorDetail i:nil="true" />
</AddressInfo>
</DrilldownModel>
我正在使用以下方法尝试从文档中获取值:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/MY.API.Models"
xmlns:d2p1="http://schemas.datacontract.org/2004/07/MY.API.Entities.Drilldown"
>
<xsl:template match="/">
<html>
<body>
<xsl:value-of select="//AddressInfo/d2p1:AddressNumber"/>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
但是我没有取回值。如果我删除默认命名空间 xmlns="http://schemas.datacontract.org/2004/07/MY.API.Models
,我可以检索该值。
有什么问题吗?
意识到默认命名空间也适用于没有命名空间前缀的后代元素,并且在 xsl:stylesheet
上声明默认命名空间不会影响 XSLT 中的 XPath。
因此,在您的 XSLT 中,为默认命名空间定义一个命名空间前缀:
xmlns:i="http://schemas.datacontract.org/2004/07/MY.API.Models"
然后替换
<xsl:value-of select="//AddressInfo/d2p1:AddressNumber"/>
和
<xsl:value-of select="//m:AddressInfo/d2p1:AddressNumber"/>
这样您就可以在它所在的 http://schemas.datacontract.org/2004/07/MY.API.Models
命名空间中选择 AddressInfo
个元素。
我从 ASP.NET 网络 API 中获得了 XML 的以下片段:
<DrilldownModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/MY.API.Models">
<AddressInfo xmlns:d2p1="http://schemas.datacontract.org/2004/07/MY.API.Entities.Drilldown">
<d2p1:AddressNumber>4213</d2p1:AddressNumber>
<d2p1:AddressUseType>RESIDENTIAL</d2p1:AddressUseType>
<d2p1:EncryptedParcelId i:nil="true" />
<d2p1:GisError i:nil="true" />
<d2p1:GisErrorDetail i:nil="true" />
</AddressInfo>
</DrilldownModel>
我正在使用以下方法尝试从文档中获取值:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/MY.API.Models"
xmlns:d2p1="http://schemas.datacontract.org/2004/07/MY.API.Entities.Drilldown"
>
<xsl:template match="/">
<html>
<body>
<xsl:value-of select="//AddressInfo/d2p1:AddressNumber"/>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
但是我没有取回值。如果我删除默认命名空间 xmlns="http://schemas.datacontract.org/2004/07/MY.API.Models
,我可以检索该值。
有什么问题吗?
意识到默认命名空间也适用于没有命名空间前缀的后代元素,并且在 xsl:stylesheet
上声明默认命名空间不会影响 XSLT 中的 XPath。
因此,在您的 XSLT 中,为默认命名空间定义一个命名空间前缀:
xmlns:i="http://schemas.datacontract.org/2004/07/MY.API.Models"
然后替换
<xsl:value-of select="//AddressInfo/d2p1:AddressNumber"/>
和
<xsl:value-of select="//m:AddressInfo/d2p1:AddressNumber"/>
这样您就可以在它所在的 http://schemas.datacontract.org/2004/07/MY.API.Models
命名空间中选择 AddressInfo
个元素。