我正在使用Application.ExportXML编写代码,该代码将各种Access查询导出到单个XML文件。到目前为止我有代码并且它正在工作,但我想在将要导出的查询数据中标记每条记录。例如,我在XML文件中列出了一个名为“portOfCallList”的查询,但我希望每条记录都标记为“portOfCall”。现在一条记录看起来像这样:
- <portOfCallList>
<arrivalDate>2015-07-17T00:00:00</arrivalDate>
<departureDate>2015-07-17T00:00:00</departureDate>
<portOfCallName>Southampton</portOfCallName>
<portOfCallCode>GBSOU</portOfCallCode>
</portOfCallList>
我希望它看起来像这样:
- <portOfCallList>
- <portOfCall>
<arrivalDate>2015-07-17T00:00:00</arrivalDate>
<departureDate>2015-07-17T00:00:00</departureDate>
<portOfCallName>Southampton</portOfCallName>
<portOfCallCode>GBSOU</portOfCallCode>
</portOfCall>
'And then have various other records also labeled "portOfCall" before ending with
</portOfCallList>.
这是我需要添加到代码中的唯一内容,因为其余的代码完成了我需要它做的事情。如果需要,我可以发布代码。
如果我能进一步解释,请告诉我,谢谢!
柯比
答案 0 :(得分:1)
要设置xml文件的样式,您需要使用XSLT stylesheet。 XSL是一种用于转换xml文档的特殊用途声明性语言。
因此,根据MS Access的输出,您可以使用MS Access VBA将原始输出xml转换为所需的修改xml格式:
首先,将以下内容另存为.xsl文件:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8"/>
<xsl:template match="/">
<xsl:element name="portOfCallList"><xsl:text>
</xsl:text>
<xsl:for-each select="//portOfCallList">
<xsl:element name="portOfCall"><xsl:text>
</xsl:text>
<xsl:copy-of select="arrivalDate"/><xsl:text>
</xsl:text>
<xsl:copy-of select="departureDate"/><xsl:text>
</xsl:text>
<xsl:copy-of select="portOfCallName"/><xsl:text>
</xsl:text>
<xsl:copy-of select="portOfCallCode"/><xsl:text>
</xsl:text>
</xsl:element><xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:element><xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
其次,运行VBA:
Public Sub PortOfCallXML()
Dim xmlfile As Object, xslfile As Object, newxmlfile As Object
Dim xmlstr As String, xslstr As String, newxmlstr As String
Set xmlfile = CreateObject("MSXML2.DOMDocument")
Set xslfile = CreateObject("MSXML2.DOMDocument")
Set newxmlfile = CreateObject("MSXML2.DOMDocument")
xmlstr = "C:\Path\To\RawXMLFile.xml" ' ORIGINAL OUTPUT
xslstr = "C:\Path\To\XSLFile.xsl" ' FROM ABOVE SCRIPT
newxmlstr = "C:\Path\To\NewXMLFile.xml" ' NEW TRANSFORMED FILE
xmlfile.async = False
xmlfile.Load xmlstr
xslfile.async = False
xslfile.Load xslstr
xmlfile.transformNodeToObject xslfile, newxmlfile
newxmlfile.Save newxmlstr
Set xmlfile = Nothing
Set xslfile = Nothing
Set newxmlfile = Nothing
MsgBox "XML File successfully transformed!", vbInformation, "XML Transform Successful"
End Sub
输出看起来像预期的那样(我重复发布的数据作为示例):
<?xml version="1.0" encoding="UTF-8"?>
<portOfCallList>
<portOfCall>
<arrivalDate>2015-07-17T00:00:00</arrivalDate>
<departureDate>2015-07-17T00:00:00</departureDate>
<portOfCallName>Southampton</portOfCallName>
<portOfCallCode>GBSOU</portOfCallCode>
</portOfCall>
<portOfCall>
<arrivalDate>2015-07-17T00:00:00</arrivalDate>
<departureDate>2015-07-17T00:00:00</departureDate>
<portOfCallName>Southampton</portOfCallName>
<portOfCallCode>GBSOU</portOfCallCode>
</portOfCall>
...
</portOfCallList>