问题描述
我遇到了不友好且半生不熟的xml文件,这些文件类似于以下内容:
I have a whack of unfriendly and half-baked xml files that resemble the following:
<root>
<child0><name0>Bob Dylan</name0></child0>
<child1><name1>Daft Punk</name1></child1>
<child2><name2>Nine Inch Nails</name2></child2>
</root>
我希望将每个文件转换为以下内容:
and i wish to transform each file into the following:
<root><children>
<child><name>Bob Dylan</name></child>
<child><name>Daft Punk</name></child>
<child><name>Nine Inch Nails</name></child>
</children>
</root>
每个文件没有确定数量的子代。有些只有< child0>
,而有些只有< child0> ...< child10>
。孩子中的元素也没有确定,例如。名称[0],等等。
each file does not have a deterministic number of children. some have only <child0>
while others have <child0> ... <child10>
. the elements within children are also not determined, eg. name[0], etc.
所以我想遍历每个孩子(也许带通配符或以-或??开头)以匹配数字,总是终止子项和子项的子项。
so i would like to walk through each child (perhaps with a wildcard or ends-with, or ??) to match the numeral that is always terminating the child and childs's child element.
这不起作用,但类似于:
this doesnt work but something along the lines of:
<xsl:for-each select="child*" >
<child>
<name><xsl:value-of select="name[index]"></name>
</child>
</xsl:for-each>
我见过很多关于选择,条件和匹配条件的示例,这些条件涉及选择元素中的内容(或通过位置或索引的元素)...
,因为那是应该完成的方式。
ive seen plenty of examples of select,if and match conditions that deal with selecting the content within a element (or an element by way of position or index)...because thats the way it should be done.
但是我有半熟xml。
but i have valid yet half-baked xml.
推荐答案
这是一个简单的,面向推送的解决方案,可以满足您的需求。请注意,它可以使用XSLT / XPath 1.0或2.0。
Here is a straightforward, push-oriented solution that accomplishes what you want. Note that it will work using either XSLT/XPath 1.0 or 2.0.
此XSLT何时:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output omit-xml-declaration="yes" indent="yes" />
<xsl:strip-space elements="*" />
<xsl:template match="/*">
<root>
<children>
<xsl:apply-templates />
</children>
</root>
</xsl:template>
<xsl:template match="*[starts-with(name(), 'child')]">
<child>
<xsl:apply-templates />
</child>
</xsl:template>
<xsl:template match="*[starts-with(name(), 'name')]">
<name>
<xsl:apply-templates />
</name>
</xsl:template>
</xsl:stylesheet>
...应用于原始XML:
<root>
<child0>
<name0>Bob Dylan</name0>
</child0>
<child1>
<name1>Daft Punk</name1>
</child1>
<child2>
<name2>Nine Inch Nails</name2>
</child2>
</root>
...产生想要的结果:
<root>
<children>
<child>
<name>Bob Dylan</name>
</child>
<child>
<name>Daft Punk</name>
</child>
<child>
<name>Nine Inch Nails</name>
</child>
</children>
</root>
这篇关于xml xsl xpath转换,在元素上使用通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!