如果我有这个XSL
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html"/> <xsl:output omit-xml-declaration="yes" encoding="UTF-8"/> <xsl:template match='/'> <xsl:value-of select="//Description" /> </xsl:template> </xsl:stylesheet>
而这个XML
<ArrayOfLookupValue xmlns="http://switchwise.com.au/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <LookupValue> <Description>AGL</Description> <Value>8</Value> </LookupValue> <LookupValue> <Description>Australian Power & Gas</Description> <Value>6</Value> </LookupValue> <LookupValue> <Description>EnergyAustralia</Description> <Value>13</Value> </LookupValue> <LookupValue> <Description>Origin Energy</Description> <Value>9</Value> </LookupValue> <LookupValue> <Description>TRU Energy</Description> <Value>7</Value> </LookupValue> </ArrayOfLookupValue>
我如何从这一行实际获得一些数据:
<xsl:value-of select="//Description" />
我花了好几个小时就得到了这个结论,我得出的结论是xmlns = namespace是导致我悲痛的原因.
任何帮助非常感谢.
顺便说一句,XML来自一个Web服务,所以我不能只是“改变”它 – 我可以预处理它,但这并不理想……
解决方法
这是XPath和XSLT最常见的FAQ.
简短的回答是,在XPath中,未加前缀的名称被认为属于“无名称空间”.但是,在具有默认命名空间的文档中,未加前缀的名称属于默认命名空间.
因此,对于这样的文件表达
//Description
什么都不选择(因为文档中没有描述(或任何其他)元素属于“无名称空间” – 所有元素名称都属于默认名称空间).
解:
在XSLT中定义一个名称空间,该名称空间与XML文档的默认名称空间具有相同的namespace-uri().然后使用如此定义的命名空间的前缀作为Xpath表达式中使用的任何名称:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:x="http://switchwise.com.au/"> <xsl:output method="html"/> <xsl:output omit-xml-declaration="yes" encoding="UTF-8"/> <xsl:template match='/'> <xsl:copy-of select="//x:Description" /> </xsl:template> </xsl:stylesheet>
将此转换应用于提供的XML文档时:
<ArrayOfLookupValue xmlns="http://switchwise.com.au/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <LookupValue> <Description>AGL</Description> <Value>8</Value> </LookupValue> <LookupValue> <Description>Australian Power & Gas</Description> <Value>6</Value> </LookupValue> <LookupValue> <Description>EnergyAustralia</Description> <Value>13</Value> </LookupValue> <LookupValue> <Description>Origin Energy</Description> <Value>9</Value> </LookupValue> <LookupValue> <Description>TRU Energy</Description> <Value>7</Value> </LookupValue> </ArrayOfLookupValue>
产生了想要的正确结果:
<Description xmlns="http://switchwise.com.au/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" >AGL</Description> <Description xmlns="http://switchwise.com.au/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" >Australian Power & Gas</Description> <Description xmlns="http://switchwise.com.au/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" >EnergyAustralia</Description> <Description xmlns="http://switchwise.com.au/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" >Origin Energy</Description> <Description xmlns="http://switchwise.com.au/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" >TRU Energy</Description>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。