经典ASP更新XML中的子节点

时间:2009-10-30 14:47:16

标签: xml vbscript asp-classic

我正在尝试更新XML文件的子节点IE更改值。

XML文件如下所示:

<user>
  <firstname>Andre</firstname>
  <lastname>Bruton</lastname>
</user>

这是我的经典asp代码:

users_firstname = "Tristan"  ''# New code to put in the XML file

Set xmlObj = Server.CreateObject("MSXML2.FreeThreadedDOMDocument")
xmlObj.async = False
xmlObj.setProperty "ServerHTTPRequest", True
xmlObj.Load(cURL)
If xmlObj.parseError.errorCode <> 0 Then
  Response.Write "Error Reading File - " & xmlObj.parseError.reason & "<p>"
End If

Set xmlList = xmlObj.getElementsByTagName("user")
For Each xmlItem In xmlList
  For Each xmlItem2 In xmlItem.childNodes
    a = xmlItem2.nodeName
    if a = "firstname" then firstname = xmlItem2.text
    if a = "lastname" then lastname = xmlItem2.text
  Next
Next

If firstname <> users_firstname Then
  Set nodeBook = xmlObj.selectSingleNode("//firstname")
  nodeBook.setAttribute "firstname", users_firstname
  Response.Write nodeBook.getAttribute("firstname")
  xmlObj.save(cDir & cFile)
End If

Set xmlObj = Nothing

问题在于它向XML文件添加了一个新部分,而不是将名字的值从Andre更新为Tristan。 XML看起来像这样:

<user>
<firstname firstname="Andre6">Andre</firstname>
<lastname>Bruton</lastname>
</user>

应该是什么样的:

<user>
<firstname>Tristan</firstname>
<lastname>Bruton</lastname>
</user>

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

不应使用.setAttribute方法,而应使用.Text属性。

If firstname <> users_firstname Then
    Set nodeBook = xmlObj.selectSingleNode("//firstname")
    nodeBook.Text = users_firstname
    Response.Write nodeBook.Text
    xmlObj.save(cDir & cFile)
End If