我需要在文本文件中找到它
Property Name="Manufacturer" Value="LENOVO"/>
我想要输出的结果是这样的 Manufacturer= LENOVO
我已经尝试使用两者的示例Split
,InStr
但我遇到的问题是字符串中的所有引号。一点帮助将不胜感激。如果我能得到这方面的基础知识,我打算把它放在一个数组中,以便在文本文件中查找其他内容。
请在此处参考此答案Navigating XML nodes in VBScript, for a Dummy并假设您在此位置存储了一个 xml 文件"C:\Temp\Test.xml"
测试.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Property Name="Manufacturer" Value="LENOVO" />
<Property Name="Model" Value="10RS0014US" />
<Property Name="Domain" Value="Domain.US" />
<Property Name="DomainRole" Value="1" />
<Property Name="NumberOfProcessors" Value="1" />
<Property Name="NumberOfLogicalProcessors" Value="6" />
<Property Name="TotalPhysicalMemory" Value="8417189888" />
<Property Name="Status" Value="OK" />
<Property Name="UserName" Value="Domain\User" />
</root>
脚本
Option Explicit
Dim Title,objDoc,objRoot,child,Name,Value,objNode,Manufacturer_Value,Name_Value
Title = "Navigating XML nodes in VBScript"
Set objDoc = CreateObject("MSXML.DOMDocument")
objDoc.Load "C:\Temp\Test.xml"
' Iterate over all elements contained in the <root> element:
Set objRoot = objDoc.documentElement
Name = ""
Value = ""
For Each child in objRoot.childNodes
Name = Name & child.getAttribute("Name") & vbcrlf
Value = Value & child.getAttribute("Value") & vbcrlf
Name_Value = Name_Value & child.getAttribute("Name") & " = "& child.getAttribute("Value") & vbcrlf
Next
MsgBox Name,vbInformation,Title
MsgBox Value,vbInformation,Title
MsgBox Name_Value,vbInformation,Title
'Find a particular element using XPath:
Set objNode = objDoc.selectSingleNode("/root/Property[@Name='Manufacturer']")
Manufacturer_Value = objNode.getAttribute("Value")
MsgBox "Manufacturer = " & Manufacturer_Value,vbInformation,Title
使用 RegEX 的其他方法:
Option Explicit
Dim Title,fso,s,r,m,Manufacturer_Value
Title = "Extract Value with RegEx in Vbscript"
Set fso = CreateObject("Scripting.FileSystemObject")
s = fso.OpenTextFile("C:\Temp\Test.xml").ReadAll()
Set r = New RegExp
r.Global = False
r.Pattern = "Value=\x22(\S+)\x22"
For Each m In r.Execute(s)
Manufacturer_Value = m.Submatches(0)
Next
MsgBox "Manufacturer = "& Manufacturer_Value,vbInformation,Title
第三种方法:读取文件并使用 Instr 和 Split 搜索字符串
Option Explicit
Dim Title,FSO, ReadTextFile
Dim Textline,Manufacturer,Manufacturer_Value
Title = "Read file and search for string using Instr and Split"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set ReadTextFile = FSO.OpenTextFile("C:\Temp\Test.xml", 1) ' Open the file with read only mode
Do Until ReadTextFile.AtEndOfStream
Textline = ReadTextFile.Readline()
If Instr(Lcase(Textline), Lcase("Manufacturer")) Then ' If textline contain string "Manufacturer"
Manufacturer = Split(Textline,chr(34))(1) ' Split the textline with Double quote chr(34) indicator
Manufacturer_Value = Split(Textline,chr(34))(3)
Exit Do ' If we find our string we can leave the Do ..Loop
End If
Loop ' Read through every line
Msgbox Manufacturer & " = " & Manufacturer_Value,vbInformation,Title