0

我正在创建一个 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>

现在我的应用程序读取文件名,如果操作节点是“添加”,它会复制文件并将操作节点转换为“保留”

问题

我现在想做的是在每次操作后保存这个文件。如果在保存 XML 时出现任何错误,我应该能够制作 XML 的副本,以便在操作中再次使用它。

4

1 回答 1

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
于 2012-06-22T15:09:07.520 回答