如何解决MSXML2 - 如何搜索特定节点并替换其子节点
我需要按名称搜索 <deviceset>
元素(例如 name="DB_")并用更新的数据替换其子树 <technologies>
。
到目前为止,我制作了以正确结构返回 MSXML2.IXMLDOMElement
<technologies>
的函数,但我不知道如何在主文档中进行搜索和替换。
我正在尝试这种方法
'Select everything from table Interlink - This table contains element's names
Dim RS As Recordset
Set RS = CurrentDb.OpenRecordset("SELECT * FROM Interlink")
'Create new document and load the file
Dim odoc As DOMDocument60
Set odoc = New DOMDocument60
odoc.async = False
odoc.Load CurrentProject.Path & "\JLC_pattern.xml"
Dim Tech As IXMLDOMElement 'I can set this to contain updated <technologies> subtree
'is it better to use IXMLDOMNode? or IXMLDOMDocumentFragment?
Dim devSets As IXMLDOMNodeList 'Collection ?
Dim devSet As IXMLDOMNode 'Node?
'Loop through the recordset,search for elements and replace the subtree <technologies>
Do Until RS.EOF
'Recordset Now contains the deviceset name attribute
Debug.Print RS.Fields("lbrDeviceSetName") ' first record contains "DB_"
'I can't find the right method to find the node or collection
'I have tried:
Set devSets = odoc.getElementsByTagName("deviceset") 'and
Set devSets = odoc.selectNodes("//eagle/drawing/library/devicesets/deviceset")
'but devSets collection is always empty
For Each devSet In devSets
Debug.Print devSet.baseName ' this does not loop
Next devSet
'I made a function that returns IXMLDOMNode with needed data structure
'Once I find the node I need to replace the subtree
'and move to the next deviceset name
RS.MoveNext
Loop
'Save the modified XML document to disk
odoc.Save CurrentProject.Path & "\SynthetizedDoc.xml"
RS.Close
'Cleanup...
循环遍历节点集合并搜索记录集可能比循环遍历记录集并搜索节点更容易。
谁能给我一个线索?
编辑:我用 for each loop
模式 XML 在这里JLC_Pattern.xml
编辑 2: <technologies>
子树可能非常大。我不想用代码淹没这篇文章。我有一个从数据库中提取数据的函数 getTechnology(tech as string) as IXMLDOMElement
。函数输出内容可以在这里下载:IXMLDOMElement.xml 不是这个函数的问题,就是不知道怎么把这个输出插入到odoc
解决方法
这对我有用:
'Create new document and load the file
Dim oDoc As DOMDocument60
Dim devSet As IXMLDOMNode
Set oDoc = New DOMDocument60
oDoc.async = False
'https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms762632(v=vs.85)
oDoc.SetProperty "ProhibitDTD",False 'needed for MSXML6
oDoc.validateOnParse = False 'or get a DTD-related error
'"The element 'eagle' is used but not declared in the DTD/Schema."
'always test for load errors
If Not oDoc.Load("C:\Tester\JLC_pattern.xml") Then
Debug.Print oDoc.parseError.reason
Exit Sub
End If
'select a single node based on its name attribute value
Set devSet = oDoc.SelectSingleNode("/eagle/drawing/library/devicesets/deviceset[@name='DB_']")
If Not devSet Is Nothing Then
Debug.Print devSet.XML
'work with devSet child nodes...
Else
Debug.Print "node not found"
End If
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。