假设我有以下XML:
<DataDictionary numberOfFields="5">
<DataField name="Species" optype="categorical" dataType="string">
<Value value="setosa"/>
<Value value="versicolor"/>
<Value value="virginica"/>
</DataField>
<DataField name="Sepal.Length" optype="continuous" dataType="double"/>
<DataField name="Sepal.Width" optype="continuous" dataType="double"/>
<DataField name="Petal.Length" optype="continuous" dataType="double"/>
<DataField name="Petal.Width" optype="continuous" dataType="double"/>
</DataDictionary>
有人可以提供一个将所有属性名称都大写的正则表达式(例如,用于vim或sed)吗?
例如,我想numberOfFields
成为NumberOfFields
和dataType
成为DataType
。
用sed处理XML通常不是一个好主意,因为sed以基于行的方式工作,而XML并不真正关心换行。例如,您可能有
<foo bar=
"baz"/>
完全有效的XML中,使用sed(或其他纯文本工具)将很难处理。
我建议使用XSLT样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:variable name="vLower" select="'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:variable name="vUpper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@*">
<xsl:variable name="capname"
select="concat(translate(substring(name(.),1,1), $vLower, $vUpper), substring(name(.), 2))"/>
<xsl:attribute name="{$capname}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
将其放在一个文件中,例如foo.xsl
,然后使用XSLT处理器xsltproc
来运行它:
xsltproc foo.xsl foo.xml
foo.xml
您的XML文件在哪里。或者,使用xalan
:
xalan -xsl foo.xsl -in foo.xml
任何XSLT处理器都可以;对于其他人,请查看他们的联机帮助页。
其工作原理如下:
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
是应用于所有节点的身份转换(在本例中不是属性,因为它们是在其他地方处理的),并递归地应用模板。这样一来,转换的输出即为输入的副本,其中没有其他模板适用。肉在里面
<xsl:variable name="vLower" select="'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:variable name="vUpper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:template match="@*">
<xsl:variable name="capname"
select="concat(translate(substring(name(.),1,1), $vLower, $vUpper), substring(name(.), 2))"/>
<xsl:attribute name="{$capname}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
这适用于所有属性(@*
)。
concat(translate(substring(name(.),1,1), $vLower, $vUpper), substring(name(.), 2))
是属性名称的大写版本,并将其分配给变量capname
。然后
<xsl:attribute name="{$capname}">
<xsl:value-of select="."/>
</xsl:attribute>
插入一个具有大写名称和旧值的新属性,以代替旧的非大写属性。
这将与所有有效的XML输入一起使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句