【发布时间】:2021-04-20 08:52:42
【问题描述】:
我有这个 XML 文件
我需要通过其名称(例如 name="DB_")搜索 <deviceset> 元素并将其子子树 <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扩展了VBA代码
模式 XML 在这里JLC_Pattern.xml
编辑 2:<technologies> 子树可能非常大。我不想用代码淹没这篇文章。我有一个函数getTechnology(tech as string) as IXMLDOMElement 从数据库中提取数据。函数输出内容可以在这里下载:IXMLDOMElement.xml问题不是这个函数,我只是不知道怎么把这个输出插入到oDoc的正确位置
【问题讨论】:
-
this 有用吗?
-
查看 XPath 以查询特定节点的 XML: - XPath Sample - XPath Sample
-
请在帖子正文中包含一个示例 XML,而不是作为minimal reproducible example 的图像。另请参阅why。
-
如果您可以共享示例 XML 文件,您就更有可能获得帮助。没有人愿意根据图像重新输入。
-
帖子底部有一个指向 XML 的超链接