gpt4 book ai didi

xml - XSLT 删除根命名空间并将命名空间添加到另一个元素

转载 作者:行者123 更新时间:2023-12-04 17:02:29 25 4
gpt4 key购买 nike

我有一个输入 xml -

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root xmlns="http://www.somenamespace">
<Child1>
<A>a</A>
<B>b</B>
</Child1>
<Child2>
<C>c</C>
<D>d</D>
</Child2>
</Root>

我希望转换后的输出 xml 从根目录中删除命名空间并将其添加到 Element Child1 中,而不是这样 -
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<NewRoot>
<NewChild1 xmlns="http://www.somenamespace">
<A>a</A>
<B>b</B>
</NewChild1>
<NewChild2>
<C>c</C>
<D>d</D>
</NewChild2>
</NewRoot>

我的 xslt 看起来像-
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.somenamespace"
xmlns:test="http://www.somenamespace"
exclude-result-prefixes="test">
<xsl:output method="xml" indent="yes" version="1.0" encoding="UTF-8" standalone="yes"/>
<xsl:template match="/">
<NewRoot>
<xsl:apply-templates select="test:Root/test:Child1"/>
<xsl:apply-templates select="test:Root/test:Child2"/>
</NewRoot>
</xsl:template>
<xsl:template match="test:Root/test:Child1">
<NewChild1> <xsl:value-of select="current()"/> </NewChild1>
</xsl:template>
<xsl:template match="test:Root/test:Child2">
<NewChild2> <xsl:value-of select="current()"/> </NewChild2>
</xsl:template>
</xsl:stylesheet>

目前,这会将命名空间添加到 NewRoot 元素。

最佳答案

您可以按如下方式更改它:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:test="http://www.somenamespace"
exclude-result-prefixes="test">
<xsl:output method="xml" indent="yes" version="1.0" encoding="UTF-8" standalone="yes"/>
<xsl:template match="/">
<NewRoot>
<xsl:apply-templates select="test:Root/test:Child1"/>
<xsl:apply-templates select="test:Root/test:Child2"/>
</NewRoot>
</xsl:template>
<xsl:template match="test:Root/test:Child1">
<test:NewChild1> <xsl:value-of select="current()"/> </test:NewChild1>
</xsl:template>
<xsl:template match="test:Root/test:Child2">
<NewChild2> <xsl:value-of select="current()"/> </NewChild2>
</xsl:template>
</xsl:stylesheet>

IE。不要声明默认命名空间( xmlns="..." ),而是将 NewChild1 明确地放在 http://www.somenamespace 中命名空间。

这会按照您的要求进行操作,即修改您的样式表以“从根目录中删除命名空间并将其添加到 Element Child1”;但它不会产生所有细节的示例输出(例如, <A><B> 元素仍未保留,因为您没有寻求帮助)。与其完全重写您的样式表来重现示例输出中可能不是您想要关注的方面,我将把它留在那里,让您提供关于您特别需要帮助的其他方面的反馈。

在所有这些中,如果您确保了解命名空间声明、命名空间前缀和元素所在的命名空间之间的区别,它将节省时间并使交流更容易。

关于xml - XSLT 删除根命名空间并将命名空间添加到另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38214327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com