简体   繁体   English

重命名同一级别同名标签的xml标签

[英]Rename xml tag for tag with same name on same level

My project needs to convert xml to rename tag which have the same name as other tag on same level.我的项目需要将xml转换为与同一级别的其他标签同名的重命名标签。 I try to use the function docucment.renameNode(), but it seems not working... The difficulty is how identify the correct tag to rename.我尝试使用函数 docucment.renameNode(),但它似乎不起作用......困难在于如何识别要重命名的正确标签。

Exemple, here the source xml :例如,这里是源 xml:

<A>
  <B>
    <C></C>
  </B>
  <B>
    <D>
      <E></E>
    </D>
  </B>
  <B>
    <F></F>
  </B>
</A>

Here the new expected xml :这里是新的预期 xml:

<A>
  <B_1>
    <C></C>
  </B_1>
  <B_2>
    <D>
      <E></E>
    </D>
  </B_2>
  <B_3>
    <F></F>
  </B_3>
</A>

I wonder why you want to do this conversion: Putting sequence numbers into tag names is generally considered a bad idea, since it usually makes the XML harder to process subsequently.我想知道为什么要进行这种转换:将序列号放入标记名称通常被认为是一个坏主意,因为它通常会使 XML 更难随后处理。

But if you really want to do it, it's a very straightforward XSLT transformation.但如果您真的想这样做,这是一个非常简单的 XSLT 转换。 In XSLT 3.0 it's在 XSLT 3.0 中它是

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform version="3.0">
  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:template match="B">
    <xsl:element name="B_{count(preceding-sibling::B)+1}">
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>
</xsl:transform>

It's also easy enough with XSLT 1.0, just a few more lines of code to add an identity template in place of the xsl:mode declaration.使用 XSLT 1.0 也很简单,只需多几行代码即可添加标识模板来代替 xsl:mode 声明。 Still a lot easier than hand-coding it in Java.仍然比在 Java 中手动编码要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM