我是 Visual Basic 的新手,所以我想从一开始就原谅自己。
下面的代码应该得到一个节点列表,其中包含所有节点,其中 Name
的 InnerText
等于名为 membername
的字符串。这部分似乎工作完美,但之后我还想检查此列表中是否已存在节点 Logout
。这样我想防止复制 xml 数据库中的数据。不幸的是,它没有像我尝试的那样工作。它不断复制所有数据。那么我的错误是什么??
XML 文件
<?xml version="1.0" encoding="utf-16"?>
<Times>
<Shift>
<Name>Philipp</Name>
<Login>14:11</Login>
<Date>25.03.2013</Date>
<Logout>14:11</Logout> ' Don't generate again ....
</Shift>
<Shift>
<Name>Philipp</Name>
<Login>14:11</Login>
<Date>25.03.2013</Date>
<Logout>14:11</Logout> ' Generate Logout node
</Shift>
</Times>
视觉基本代码
If File.Exists(Filename) Then
DOMDocument.Load(Filename)
Dim RootElement As XmlElement = DOMDocument.DocumentElement
Dim ListOfTitles As XmlNodeList = DOMDocument.GetElementsByTagName("Name")
For Each Node As XmlNode In ListOfTitles
If Node.InnerText = memberName Then
Dim logout = Node.SelectNodes("Logout")
If Not logout Is Nothing Then
Dim NewElement As XmlElement = DOMDocument.CreateElement("Logout")
NewElement.InnerText = DateTime.Now.ToShortTimeString()
Dim Parent As XmlNode = Node.ParentNode
Parent.AppendChild(NewElement)
DOMDocument.Save(Filename)
End If
End If
Next
End If
最佳答案
logout
被设置为空对象,因此 If Not logout is Nothing Then
等同于 If True Then
。请参阅:http://msdn.microsoft.com/en-us/library/hcebdtae.aspx . IXMLElement.selectNodes(expression)
方法总是返回一个对象。要修复,请改为检查注销的长度值。
If logout.Count > 0 Then
或使用 selectSingleNode
如果没有找到节点则返回 NULL
。
关于xml - 在 Visual Basic 中将数据添加到 XML 文件的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15616421/