确实,请考虑XSLT,这是一种声明性的专用语言(与 SQL 相同的类型),旨在将 XML 文件从各种结构转换为最终用途格式,包括其他 XML、HTML 甚至 txt/csv 文件。
具体来说,您需要为每个 Value 节点。将 XSLT 中的 <mytable> 更改为 MS Access 中所需的表名称,并将 <Source> 更改为该新表中所需的字段名称。
XSLT 脚本(另存为.xsl 文件以在VBA 中加载)
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" method="xml"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/Codes">
<xsl:copy>
<xsl:apply-templates select="*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*/*">
<xsl:apply-templates select="*"/>
</xsl:template>
<xsl:template match="*[name()='Value']">
<mytable>
<Source><xsl:value-of select="name(parent::*)"/></Source>
<xsl:copy-of select="."/>
</mytable>
</xsl:template>
</xsl:transform>
VBA (注意转换的输出文件是在Access中导入的)
Public Sub TransformAndImportXML()
' INCLUDE Microsoft XML, v3.0 REFERENCE
Dim xmlDoc As New MSXML2.DOMDocument, xslDoc As New MSXML2.DOMDocument, newDoc As New MSXML2.DOMDocument
xmlDoc.Load "C:\Path\To\XML\Input.xml"
xslDoc.Load "C:\Path\To\XML\File.xsl"
xmlDoc.transformNodeToObject xslDoc, newDoc
newDoc.Save "C:\Path\To\XML\Output.xml"
Set xmlDoc = Nothing: Set xslDoc = Nothing: Set newDoc = Nothing
Application.ImportXML "C:\Path\To\XML\Output.xml"
MsgBox "Successfully transformed and imported XML!", vbInformation
End Sub
XML输出
<?xml version="1.0" encoding="utf-8"?>
<Codes>
<mytable>
<Source>ABC</Source>
<Value>1234567891011</Value>
</mytable>
<mytable>
<Source>ABC</Source>
<Value>1234567891110</Value>
</mytable>
<mytable>
<Source>ABC</Source>
<Value>1234567891022</Value>
</mytable>
<mytable>
<Source>DEF</Source>
<Value>12116360102</Value>
</mytable>
<mytable>
<Source>DEF</Source>
<Value>65416360402</Value>
</mytable>
<mytable>
<Source>DEF</Source>
<Value>68559760202</Value>
</mytable>
</Codes>
MS Access 导入(mytable 内容)
Source Value
ABC 1234567891011
ABC 1234567891110
ABC 1234567891022
DEF 12116360102
DEF 65416360402
DEF 68559760202