我正在尝试读取XML文件(格式不正确)。下面是我的实际XML文件。
<?xml version="1.0" encoding="UTF-8"?><Report time="8/18/2017 12:54:42"><Table>TABLE</Table><Application>Fruits</Application><Environment>AMAZON</Environment><Group>FOREST</Group><SubGroup>RAINFOREST</SubGroup><Row>3</Row><Release>SEPT</Release><Result>Pass</Result><Testname>HEALTHCHECK</Testname><Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath></Report>
现在我正在尝试阅读此内容并保存XML格式,但无法继续使用。
我想要的格式并保存:
<?xml version="1.0" encoding="UTF-8"?>
<Report time="8/18/2017 12:54:42">
<Table>TABLE</Table>
<Application>Fruits</Application>
<Environment>AMAZON</Environment>
<Group>FOREST</Group>
<SubGroup>RAINFOREST</SubGroup>
<Row>3</Row>
<Release>SEPT</Release>
<Result>Pass</Result>
<Testname>HEALTHCHECK</Testname>
<Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath>
</Report>
我可以检查格式但无法保存。以下是我尝试过的代码。
Public Sub Create_Report()
myFile = "C:\Prac_Session\OLB.xml"
Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(myFile, ForReading, False)
Do While Not txtStream.AtEndOfStream
Debug.Print txtStream.ReadLine
Tempstr = ">" & vbNewLine & "<"
a = Replace(txtStream.ReadLine, "><", Tempstr)
Debug.Print a
''Now to save.??''
Loop
txtStream.Close
End Sub
答案 0 :(得分:2)
我相信这样做会:
Sub foo()
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String
fileSpec = "C:\Prac_Session\OLB.xml" 'change the path to whatever yours ought to be
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll 'would use read all to read the whole file into memory
'Do While Not objTS.AtEndOfStream
' strContents = strContents & " " & objTS.ReadLine 'Read line by line and store all lines in strContents
'Loop
Tempstr = ">" & vbCrLf & "<" 'instead of vbNewLine
strContents = Replace(strContents, "><", Tempstr)
objTS.Close
Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
End Sub
答案 1 :(得分:2)
MSXML DOM库中包含一个漂亮的打印功能。此博文The Excel Development Platform_ VBA - Ease Xml debugging wth Xml document pretty print有一些示例源代码