xml 动态元素名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27931/
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 11:57:44  来源:igfitidea点击:

Dynamic Element Names

xmlxsltnamespaces

提问by JPLemme

I want to transform an XML document. The source XML looks like this:

我想转换一个 XML 文档。源 XML 如下所示:

<svc:ElementList>
    <svc:Element>
        <Year>2007</Year>
    </svc:Element>
    <svc:Element>
        <Year>2006</Year>
    </svc:Element>
    <svc:Element>
        <Year>2005</Year>
    </svc:Element>
</svc:ElementList>

I want to turn that into:

我想把它变成:

<ElementList>
    <NewTag2007/>
    <NewTag2006/>
    <NewTag2005/>
</ElementList>

The following line of code isn't working:

以下代码行不起作用:

<xsl:element name="{concat('NewTag',Element/Year)}"/>

The output is a series of elements that look like this: < NewTag >. (Without the spaces...)

输出是一系列如下所示的元素:< NewTag >。(没有空格...)

"//Element/Year", "./Element/Year", and "//svc:Element/Year"don't work either. One complication is that the "Element" tag is in the "svc" namespace while the "Year" tag is in the default namespace.

"//Element/Year""./Element/Year""//svc:Element/Year"也不起作用。一个复杂的问题是“Element”标签在“svc”命名空间中,而“Year”标签在默认命名空间中。

So anyway, am I facing a namespace issue or am I mis-using the "concat()" function?

所以无论如何,我是面临命名空间问题还是我误用了“concat()”函数?

采纳答案by jelovirt

Probably namespace issues and maybe one with current context. For source (with added namespace declaration to make it well-formed xml)

可能是命名空间问题,也可能是当前上下文的问题。对于源代码(添加命名空间声明以使其成为格式良好的 xml)

<svc:ElementList xmlns:svc="svc">
  <svc:Element>
    <Year>2007</Year>
  </svc:Element>
  <svc:Element>
    <Year>2006</Year>
  </svc:Element>
  <svc:Element>
    <Year>2005</Year>
  </svc:Element>
</svc:ElementList>

the stylesheet

样式表

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:svc="svc"
                version="1.0">
  <xsl:template match="svc:ElementList">
    <xsl:element name="{local-name()}">
      <xsl:for-each select="svc:Element">
        <xsl:element name="{concat('NewTag', Year)}"/>
      </xsl:for-each>
    </xsl:element>
  </xsl:template> 
</xsl:stylesheet>

will give you the output you need. Note that svc:Elementneeds to be selected using namespace prefixed and that the context when generating the new tags is svc:Element, not svc:ElementList.

会给你你需要的输出。请注意,svc:Element需要使用带前缀的命名空间进行选择,并且生成新标签时的上下文是svc:Element,而不是svc:ElementList