有多种方法可以做到这一点。您可以对对象使用<>
and@
语法XDocument
来深入了解所需的元素,如下所示:
Sub Timestamp(idChosen As String)
Dim doc As XDocument = XDocument.Load("Dictionary Resources\Dictionary.xml")
Dim word As XElement = doc.<Root>.<Word>.FirstOrDefault(Function(x) x.@ID = idChosen)
If word IsNot Nothing Then
word.<Timestamp>.First().SetValue(Date.Now)
doc.Save("Dictionary Resources\Dictionary.xml")
End If
End Sub
或者您可以使用 XPath 来选择元素,如下所示:
Sub Timestamp(idChosen As String)
Dim doc As XDocument = XDocument.Load("Dictionary Resources\Dictionary.xml")
Dim timeStamp As XElement = doc.XPathSelectElement("/Root/Word[@ID='" & idChosen & "']/Timestamp")
If timeStamp IsNot Nothing Then
timeStamp.SetValue(Date.Now)
doc.Save("Dictionary Resources\Dictionary.xml")
End If
End Sub
或者,您可以使用查询语法来选择元素,如下所示:
Sub Timestamp(idChosen As String)
Dim doc As XDocument = XDocument.Load("Dictionary Resources\Dictionary.xml")
Dim t As XElement = _
(
From word In doc.<Root>.<Word>
Where word.@ID = idChosen
Select word.<Timestamp>.FirstOrDefault()
).FirstOrDefault()
If t IsNot Nothing Then
t.SetValue(Date.Now)
doc.Save("Dictionary Resources\Dictionary.xml")
End If
End Sub
或者,如果您想使用查询语法而不使用<>
and@
语法,您可以这样做,如下所示:
Sub Timestamp(idChosen As String)
Dim doc As XDocument = XDocument.Load("Dictionary Resources\Dictionary.xml")
Dim t As XElement = _
(
From word In doc.Root.Elements("Word")
Where word.Attributes("ID").Any(Function(x) x.Value = idChosen)
Select word.Element("Timestamp")
).FirstOrDefault()
If t IsNot Nothing Then
t.SetValue(Date.Now)
doc.Save("Dictionary Resources\Dictionary.xml")
End If
End Sub
或者,如果您不关心实际的 XML 文档结构,而只想找到Word
具有该 ID 的第一个元素,而不管它位于文档树中的什么位置,您可以像这样选择元素:
Dim word As XElement = doc...<Word>.FirstOrDefault(Function(x) x.@ID = idChosen)
或者:
Dim timeStamp As XElement = doc.XPathSelectElement("//Word[@ID='" & idChosen & "']/Timestamp")
或者:
Dim t As XElement = _
(
From word In doc.Descendants("Word")
Where word.@ID = idChosen
Select word.<Timestamp>.FirstOrDefault()
).FirstOrDefault()
或者:
Dim t As XElement = _
(
From word In doc.Descendants("Word")
Where word.Attributes("ID").Any(Function(x) x.Value = idChosen)
Select word.Element("Timestamp")
).FirstOrDefault()
就个人而言,我建议使用选择节点的 XPath 方法,因为它简短、简单、易于阅读,而且它使用的是行业标准的查询语言,而不是 Microsoft 的专有 LINQ 技术,但这只是我 :)