抱歉我的英语不好,但我会尽力正确描述我的问题。我有一个VBA代码。这是:
Sub TestXML()
Dim doc As New DOMDocument
Const filePath As String = "D:\Test3.xml"
Dim isLoaded As Boolean
isLoaded = doc.Load(filePath)
If isLoaded Then
Dim oAttributes As MSXML2.IXMLDOMNodeList
Set oAttributes = doc.getElementsByTagName("Operation")
Dim attr As MSXML2.IXMLDOMAttribute
Dim node As MSXML2.IXMLDOMElement
Dim tdate As String
tdate = Format(Now(), "yyyy-mm-dd")
For Each node In oAttributes
For Each attr In node.Attributes
If attr.Name = "Client" Then
If attr.Value <> "UL" Then
attr.Value = "UL"
End If
ElseIf attr.Name = "Date" Then
If attr.Value <> "tdate" Then
attr.Value = tdate
End If
End If
Next attr
Next node
doc.Save filePath
End If
End Sub
问题是 - 仅当元素“Operation”不存在时,如何创建值为“UL”的属性“Client”? 这是我使用的 .xml 文件示例:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
<Operations>
<Operation Date="2018-11-06" Client="UL"/>
<Operation Date="2018-11-06" Client="UL"/>
<Operation Date="2018-11-06"/>
</Operations>
</Document>
谢谢!
最佳答案
尝试读取属性节点,如果不存在则创建它:
For Each node In oAttributes
If (node.getAttributeNode("Client") Is Nothing) Then
'// add missing attrib
node.setAttribute "Client", "UL"
End If
您当前的代码似乎希望所有元素都具有 Client=UL,以简单地实现这一点:
For Each node In oAttributes
node.setAttribute "Client", "UL"
Next node
这将根据需要覆盖或创建属性。
关于excel - 如果不存在,如何创建具有特定值的属性 - VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53172131/