在 VBA 中将 XML 文件转换为字符串变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22297472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:15:58  来源:igfitidea点击:

Convert XML file to String variable in VBA

xmlexcelvbaexcel-vba

提问by Barney G

I'm looking to convert the contents of an XML file into a String variable in excel VBA so that I can search the file for a specific string.

我希望在 Excel VBA 中将 XML 文件的内容转换为字符串变量,以便我可以在文件中搜索特定字符串。

However I don't know how to do the initial conversion from XML file to String variable. All I've been able to do so far is load the XML document, and from there I'm stuck.

但是我不知道如何进行从 XML 文件到 String 变量的初始转换。到目前为止我所能做的就是加载 XML 文档,然后我就卡住了。

Public Function DetermineSpecifiedChange(ByVal vstrInputGBOMPath As String, ByVal vstrInputPDPPath As String)


Dim strPDPString As String
Dim strGBOMString As String

Dim xmlGBOM As New DOMDocument60

Dim xmlPDP As New DOMDocument60

strPDPString = xmlPDP.Load(vstrInputPDPPath)

End Function

So far all this returns is "True", signifying that the file is being loaded.

到目前为止,所有这些返回的结果都是“True”,表示正在加载文件。

How would I go about converting the XML file into a string?

我将如何将 XML 文件转换为字符串?

采纳答案by Jean-Fran?ois Corbett

Here's a way to do what you ask:

这是一种按照您的要求进行操作的方法:

Dim FSO As Object : Set FSO = CreateObject("Scripting.FileSystemObject")    
Dim strXml As String
strXml = FSO.OpenTextFile("C:\myfile.xml").ReadAll 

回答by messed-up

Here is a function that i'm currently using in one of my old application to convert file to string.

这是我目前在我的一个旧应用程序中使用的一个函数,用于将文件转换为字符串。

Private Function FileToText(fullFilePath as String) as string
Dim nFile           As Integer
Dim baBuffer()      As Byte
Dim sPostData       As String

nFile = FreeFile
Open fullFilePath For Binary Access Read As nFile
If LOF(nFile) > 0 Then
    ReDim baBuffer(0 To LOF(nFile) - 1) As Byte
    Get nFile, , baBuffer
    sPostData = StrConv(baBuffer, vbUnicode)
End If
Close nFile FileToText = sPostData
FileToText = sPostData

This is a part of code from http://wqweto.wordpress.com/2011/07/12/vb6-using-wininet-to-post-binary-file/

这是来自http://wqweto.wordpress.com/2011/07/12/vb6-using-wininet-to-post-binary-file/的代码的一部分