How can I Find/Replace multiple strings in an xml file?

廉价感情. 提交于 2019-12-24 01:42:14

问题


I have about 600 different text strings that I need to replace within an XML file (I am using notepad++ though I can use other programs too if this would accomplish the task). The text changes are listed in a separate excel file. Is there a way that I can run a script or command to find/replace all of the strings in one shot, without having to do each one individually?

Thank you


回答1:


You could use some simple VBA to do the job from within your Excel s/s. Call the below Sub by passing in the find-replace range e.g. from the Excel VBA Immediate window (access using Alt+F11 for the VBA editor then View -> Immediate):

ReplaceXML Range("A1:B600")

Assuming A1:B600 contains the 600 find-replace strings.

After defining the below in a module (Insert -> Module from within the VBA editor (Alt+F11) ):

Option Explicit ' Use this !

Public Sub ReplaceXML(rFindReplaceRange as Range) ' Pass in the find-replace range

    Dim sBuf As String
    Dim sTemp As String
    Dim iFileNum As Integer
    Dim sFileName As String
    Dim i as Long

    ' Edit as needed
    sFileName = "C:\filepath\filename.xml"

    iFileNum = FreeFile
    Open sFileName For Input As iFileNum

    Do Until EOF(iFileNum)
        Line Input #iFileNum, sBuf
        sTemp = sTemp & sBuf & vbCrLf
    Loop

    Close iFileNum

    ' Loop over the replacements
    For i = 1 To rFindReplaceRange.Rows.Count
        If rFindReplaceRange.Cells(i, 1) <> "" Then
            sTemp = Replace(sTemp, rFindReplaceRange.Cells(i, 1), rFindReplaceRange(i, 2))
        End If
    Next i

    ' Save file

    iFileNum = FreeFile

    ' Alter sFileName first to save to a different file e.g.
    sFileName = "C:\newfilepath\newfilename.xml"
    Open sFileName For Output As iFileNum

    Print #iFileNum, sTemp

    Close iFileNum

End Sub


来源:https://stackoverflow.com/questions/15456798/how-can-i-find-replace-multiple-strings-in-an-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!