具有默认名称空间设置为xmlns的XML源的XSLT

我有一个默认命名空间的根文件的XML文档。 像这样的东西:

<MyRoot xmlns="http://www.mysite.com"> <MyChild1> <MyData>1234</MyData> </MyChild1> </MyRoot> 

parsingXML的XSLT由于默认的名称空间而无法按预期的方式工作,即当我删除名称空间时,一切都按预期工作。

这是我的XSLT:

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xsl:template match="/" > <soap:Envelope xsl:version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <NewRoot xmlns="http://wherever.com"> <NewChild> <ChildID>ABCD</ChildID> <ChildData> <xsl:value-of select="/MyRoot/MyChild1/MyData"/> </ChildData> </NewChild> </NewRoot> </soap:Body> </soap:Envelope> </xsl:template> </xsl:stylesheet> 

XSLT文档需要做些什么才能使翻译正常工作? XSLT文档究竟需要做什么?

您需要在XSLT中声明命名空间,并在XPathexpression式中使用它。 例如:

 <xsl:stylesheet ... xmlns:my="http://www.mysite.com"> <xsl:template match="/my:MyRoot"> ... </xsl:template> </xsl:stylesheet> 

请注意,如果要在XPath中引用该名称空间中的元素,则必须提供一些前缀。 虽然您可以只执行xmlns="..."而没有前缀,并且它将适用于文字结果元素,但它不适用于XPath – 在XPath中,前缀名称始终被认为是在具有空白URI的名称空间中,不pipe任何xmlns="..."在范围内。

如果您使用XSLT 2.0, xpath-default-namespace="http://www.example.com"stylesheet部分指定xpath-default-namespace="http://www.example.com"

如果这是一种名称空间问题,可以尝试在xslt文件中修改两件事情:

  • 在xsl:stylesheet标签中添加“我的”名称空间定义
  • 调用元素遍历xml文件时使用“my:”前缀。

结果

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:my="http://www.w3.org/2001/XMLSchema"> <xsl:template match="/" > <soap:Envelope xsl:version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <NewRoot xmlns="http://wherever.com"> <NewChild> <ChildID>ABCD</ChildID> <ChildData> <xsl:value-of select="/my:MyRoot/my:MyChild1/my:MyData"/> </ChildData> </NewChild> </NewRoot> </soap:Body> </soap:Envelope> </xsl:template> </xsl:stylesheet>