需要在VBA中将节点添加到XML文件而不覆盖旧节点

时间:2014-07-20 09:25:06

标签: xml vba nodes

我有一个XML,我正在导入一组注释并将其与当前日期和时间节点(Date NoteD)相关联,例如:

<Serial SerialN="3s">
<Model>3m</Model>
<Assigned>3a</Assigned>
<DateA>7/3/2014</DateA>
<DateR>N/A</DateR>
<Notes>
    <Date NoteD="7/19/2014 07:58:42 PM">
         <Entry>This is a test</Entry>
    </Date>
</Notes>
</Serial>

我想添加另一个带有新的当前日期和时间的条目,所以它看起来像这样:

<Notes>
    <Date NoteD="7/19/2014 07:58:42 PM">
         <Entry>This is a test</Entry>
    </Date>
    <Date NoteD="7/19/2014 09:45:00 PM">
         <Entry>This is another test</Entry>
    </Date>
</Notes>

问题是它会一直覆盖日期,但会添加另一个条目:

<Notes>
    <Date NoteD="7/19/2014 09:45:00 PM">
         <Entry>This is a test</Entry>
         <Entry>This is another test</Entry>
    </Date>
</Notes>

这是我的代码:

 Set x = objDom.SelectSingleNode("//Serial[@SerialN='" & TextBox1.Text & "']/Notes")
 Set Datee = objDom.createElement("Date")
 x.appendChild Datee


 Set n = objDom.SelectSingleNode("//Serial[@SerialN='" & TextBox1.Text & "']/Notes/Date")
 Set Notes = objDom.createAttribute("NoteD") 
 Notes.NodeValue = Now
 n.setAttributeNode Notes


Set t = objDom.SelectSingleNode("//Serial[@SerialN='" & TextBox1.Text & "']/Notes/Date[@NoteD='" & Notes.NodeValue & "']")
Set Note = objDom.createElement("Entry")
t.appendChild Note
Note.Text = TextBox5.Text

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

代码的第二个块应该是这样的:

Set n = objDom.SelectSingleNode("//Serial[@SerialN='" & TextBox1.Text & "']/Notes/Date")
Set Notes = objDom.createAttribute("NoteD") 
Notes.NodeValue = Now
Datee.setAttributeNode Notes

将属性添加到新创建的<Date>元素而不是现有元素。

答案 1 :(得分:0)

使用xmlDoc.DocumentElement.appendChild(xmlDoc.createElement(“ type”))

.appendChild (xmlDoc.createTextNode(vbCrLf))

With .appendChild(xmlDoc.createElement("domaine"))

 .Text = ms

 End With

With .appendChild(xmlDoc.createElement("phrase"))

 .Text = cle

 End With

结尾为