我正在创建一个VB6应用程序,它从XML文件中读取信息,然后将特定文件复制到本地工作站。 XML看起来如下所示;
<ArrayOfMediaFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MediaFile>
<fileName>Default.jpg</fileName>
<filePath>C:\Program Files\media</filePath>
<dateModified>2012-04-30T14:41:28.6893988-05:00</dateModified>
<Action>Add</Action>
</MediaFile>
<MediaFile>
<fileName>icon.jpg</fileName>
<filePath>C:\Program Files\media</filePath>
<dateModified>2012-04-30T15:43:31.2995396-05:00</dateModified>
<Action>Add</Action>
</MediaFile>
</ArrayOfMediaFile>
现在我的应用程序读取文件名,如果操作节点“添加”,它会复制文件并将操作节点转换为“keep”。
问题
我现在要做的是在每次操作后保存此文件。如果在保存XML时出现任何错误,我应该能够复制XML,我可以在操作中再次使用它。
答案 0 :(得分:1)
此代码始终将XML文件.xml备份到.backup,然后如果成功,则保存到_Processed.xml。希望这就是你想要的。
Private Function ProcessFilesFromXml(ByRef the_sXmlFileName As String) As Boolean
Dim nPosDot As Long
Dim sXmlFileNamePrefix As String
Dim sXmlFileNameSuffix As String
Dim oXmlDoc As MSXML2.DOMDocument
Dim oXmlMediaFileNode As MSXML2.IXMLDOMElement
Dim oXmlActionNode As MSXML2.IXMLDOMElement
On Error GoTo ErrorHandler
nPosDot = InStr(1, the_sXmlFileName, ".")
If (nPosDot) Then
sXmlFileNamePrefix = Left$(the_sXmlFileName, nPosDot - 1)
sXmlFileNameSuffix = Mid$(the_sXmlFileName, nPosDot)
Else
sXmlFileNamePrefix = the_sXmlFileName
sXmlFileNameSuffix = vbNullString
End If
' First of all, back up the XML file <XmlFileList>.xml to <XmlFileList>.backup . Overwrites existing backup file.
FileCopy the_sXmlFileName, sXmlFileNamePrefix & ".backup"
On Error GoTo ErrorHandler_ProcessingXml
' Load the Xml file <XmlFileList>.xml
Set oXmlDoc = New MSXML2.DOMDocument
oXmlDoc.Load the_sXmlFileName
' Iterate through each media file, and try to copy it.
For Each oXmlMediaFileNode In oXmlDoc.selectNodes("/ArrayOfMediaFile/MediaFile")
If Not CopyFileNameToLocalMachine(oXmlMediaFileNode.selectSingleNode("fileName").Text, oXmlMediaFileNode.selectSingleNode("filePath").Text) Then
Set oXmlActionNode = oXmlMediaFileNode.selectSingleNode("Action")
oXmlActionNode.Text = "keep"
End If
Next oXmlMediaFileNode
' Save under the name <XmlFileList>_Processed.xml
oXmlDoc.save sXmlFileNamePrefix & "_Processed" & sXmlFileNameSuffix
' Since we got here, things must have been fine.
ProcessFilesFromXml = True
Return_ProcessingXml:
'
Exit Function
ErrorHandler_ProcessingXml:
ProcessFilesFromXml = False
Resume Return_ProcessingXml
ErrorHandler:
Err.Raise Err.Number, Err.Source, Err.Description
End Function
Private Function CopyFileNameToLocalMachine(ByRef the_sFileName As String, ByRef the_sLocalPath As String)
' Your code here.
End Function