这个 XSLT 2.0 转换:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="vText" select=
"replace(unparsed-text('file:///c:/temp/delete/text.txt'),'\r','')"/>
<xsl:template match="/">
<document>
<xsl:analyze-string select="$vText" regex="(!(.+?)\n([^\n]+))+">
<xsl:matching-substring>
<xsl:element name="{regex-group(2)}">
<xsl:sequence select="regex-group(3)"/>
</xsl:element>
</xsl:matching-substring>
<xsl:non-matching-substring><xsl:sequence select="."/></xsl:non-matching-substring>
</xsl:analyze-string>
</document>
</xsl:template>
</xsl:stylesheet>
当应用于任何 XML 文档(未使用)并将提供的文本驻留在本地文件中时C:\temp\delete\Text.txt
:
!ITEM_NAME
Item value
!ANOTHER_ITEM
Its value
...
产生想要的正确结果:
<document>
<ITEM_NAME>Item value</ITEM_NAME>
<ANOTHER_ITEM>Its value</ANOTHER_ITEM>
...
</document>
为了更全面地测试,我们将这段文本放入文件中:
As is text
!ITEM_NAME
Item value
!ANOTHER_ITEM
Its value
As is text2
!TEST_BANG
Here's a value with !bangs!!!
!TEST2_BANG
!!!Here's a value with !more~ !bangs!!!
As is text3
转换再次产生所需的正确结果:
<document>As is text
<ITEM_NAME>Item value</ITEM_NAME>
<ANOTHER_ITEM>Its value</ANOTHER_ITEM>
As is text2
<TEST_BANG>Here's a value with !bangs!!!</TEST_BANG>
<TEST2_BANG> !!!Here's a value with !more~ !bangs!!!</TEST2_BANG>
As is text3
</document>