如何在带有 XSLT 的 XML 文档中获取根元素的标签名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/368668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:15:38  来源:igfitidea点击:

How to get tag name of root element in an XML document w/ XSLT?

xmlxsltxpath

提问by Matty

I'm interested in assigning the tag name of the root element in an xml document to an xslt variable. For instance, if the document looked like (minus the DTD):

我有兴趣将 xml 文档中根元素的标记名称分配给 xslt 变量。例如,如果文档看起来像(减去 DTD):

<foo xmlns="http://.....">
    <bar>1</bar>
</foo>

and I wanted to assign the string 'foo' to an xslt variable. Is there a way to reference that?

我想将字符串 'foo' 分配给 xslt 变量。有没有办法参考?

Thanks, Matt

谢谢,马特

回答by Dirk Vollmar

I think you want to retrieve the name of the outermost XML element. This can be done like in the following XSL sample:

我认为您想要检索最外层 XML 元素的名称。这可以在以下 XSL 示例中完成:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:variable name="outermostElementName" select="name(/*)" />

  <xsl:template match="/">
    <xsl:value-of select="$outermostElementName"/>
  </xsl:template>
</xsl:stylesheet>

Please note that there is a slight difference in XPath terminology:

请注意,XPath 术语略有不同:

The top of the tree is a root node (1.0 terminology) or document node (2.0). This is what "/" refers to. It's not an element: it's the parent of the outermost element (and any comments and processing instructions that precede or follow the outermost element). The root node has no name.

树的顶部是根节点(1.0 术语)或文档节点(2.0)。这就是“/”所指的。它不是一个元素:它是最外层元素的父元素(以及最外层元素之前或之后的任何注释和处理指令)。根节点没有名字。

See http://www.dpawson.co.uk/xsl/sect2/root.html#d9799e301

http://www.dpawson.co.uk/xsl/sect2/root.html#d9799e301

回答by Dimitre Novatchev

Use the XPath name()function.

使用 XPathname()函数。

One XPath expression to obtain the name of the top (not root!) element is:

一种用于获取顶部(不是根!)元素名称的 XPath 表达式是:

       name(/*)

       name(/*)

The name() function returns the fully-qualified name of the node, so for an element <bar:foo/>the string "bar:foo" will be returned.

name() 函数返回节点的完全限定名称,因此对于元素<bar:foo/>,将返回字符串“bar:foo”。

In case only the local part of the name is wanted (no prefix and ":"), then the XPath local-name()function should be used.

如果只需要名称的本地部分(无前缀和“:”),local-name()则应使用XPath函数。

回答by Matty

Figured it out. The function name() given the parameter * will return foo.

弄清楚了。给定参数 * 的函数 name() 将返回 foo。

回答by annakata