我有一些代码用于尝试在 VB.NET 中学习 XML 解析。(甚至不确定这是否是要走的路;只是想看看我对当前阅读内容的理解是否准确,所以请耐心等待初学者级别的编程)。
XMLQuotes = New XmlDocument
XMLQuotes.Load("XMLDocs/IKAbx.xml")
Dim nodAuthor As XmlElement = XMLQuotes.DocumentElement
Dim nodItems As XmlNodeList = nodAuthor.SelectNodes("/Authors/Author")
For i = 0 To nodItems.Count - 1
'grab info from the XML using the supplied node
authorName = GetNodeValue("Name", doc)
'etc.
'try to get a list of quotes from the author.
'the next line is the line that does not work.
Dim nodQuotes As XmlNodeList = nodReqs.SelectNodes("/Authors/Author[Name='" & Replace(nodItems(i).Item("Name").InnerXml, "'", "'") & "']/Quote")
For j = 0 To nodQuotes.Count - 1
quotes.Add nodBonSk(j).InnerXml
Next
'continue processing
Next I
这个过程效果很好,但有一个例外。如果我有一个以撇号开头的引言(例如“'Tis high in the heart... ),那么它实际上并没有找到具有适当 Name 元素的节点。它返回 0 个节点的计数并继续前进。
我曾尝试在 XML 文件中使用 &apos, ' 转义字符(甚至只尝试了纯单引号),但似乎没有任何效果。那么,我做错了什么?
Private Function GetNodeValue(nodeName As String, doc As String) As Object
Dim doc2 As XDocument = XDocument.Parse(doc)
Dim element = doc2.Root.Element(nodeName)
If IsNothing(element) Then
Return Nothing
Else
Return element.Value
End If
End Function