我正在尝试在我的XML文档中搜索字符串,并希望返回其祖先标记名称以跟踪它。
目前在我的代码中输入XML路径和字符串,并通过echo
返回标记名称。
但我想对它进行一些修改:
下面给出了我的当前代码,其中包含文本值和XML路径硬编码,并且它回显每个标记名称。
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim sFSpec : sFSpec = oFS.GetAbsolutePathName("xyz.xml")
Dim objMSXML : Set objMSXML = CreateObject("Msxml2.DOMDocument")
objMSXML.setProperty "SelectionLanguage", "XPath"
objMSXML.async = False
objMSXML.load sFSpec
If 0 = objMSXML.parseError Then
Dim sXPath : sXPath = "//*[local-name()='namespace']/*[local-name()='querySubject']/*[local-name()='queryItem'][contains(., 'SearchTerm')]/ancestor-or-self::*/*[local-name()='name']"
'//namespace//querySubject/queryItem[contains(.,'searchTerm')]/ancestor-or-self::*/name
Dim querySubject : Set querySubject = objMSXML.selectSingleNode(sXPath)
If querySubject Is Nothing Then
WScript.Echo sXPath, "failed"
Else
For Each node In objMSXML.selectNodes(sXPath)
WScript.Echo node.text
Next
End If
Else
WScript.Echo objMSXML.parseError.reason
End If
示例XML是:
<project xmlns = "https://afdsl/skdflsk/d">
<name>Abcpos</name>
<property name="included" type="hidden">true</property>
<locales>
<locale>en</locale>
<locale>de</locale>
</locales>
<defaultLocale>en</defaultLocale>
<namespace>
<name locale="en">Abcpos</name>
<name locale="de">Abcpos</name>
<lastChanged>2015-04-06T17:37:40</lastChanged>
<lastChangedBy>userx</lastChangedBy>
<property name="included" type="hidden">true</property>
<namespace>
<name locale="en">Database Layer</name>
<querySubject status="valid">
<name locale="en">qskxyz</name>
<queryItem>
<name locale="en">qixyz</name>
<hello>searchTerm</hello>
</queryItem>
</querySubject>
</namespace>
</namespace>
<namespace>
<name locale="en">Names</name>
<lastChanged>2016-01-12T12:42:46</lastChanged>
<namespace>
<name locale="en">Database Layer</name>
<querySubject status="valid">
<name locale="en">qsxyz</name>
<queryItem>
<name locale="en">myName</name>
<hello>...Hi there..</hello>
</queryItem>
</querySubject>
</namespace>
</namespace>
</project>
答案 0 :(得分:0)
如果要在XML中的任何位置列出包含用户提供的文本的所有节点的父节点名称,您可以使用以下内容:
xpath = "//*[contains(.,'" & searchtext & "')]/.."
For Each node In objMSXML.SelectNodes(xpath)
WScript.Echo node.NodeName
Next
至于处理目录中的所有XML文件,在SO和其他地方有大量的例子。