为什么Msxml DocumentElement/SelectSingleNode不返回任何内容?
DocumentElement属性和SelectSingleNode始终不返回任何内容,我已经验证了xml加载是否正确,问题似乎在于xml解析器。xml没有任何名称空间,因此不需要设置它为什么Msxml DocumentElement/SelectSingleNode不返回任何内容?,xml,vba,excel,Xml,Vba,Excel,DocumentElement属性和SelectSingleNode始终不返回任何内容,我已经验证了xml加载是否正确,问题似乎在于xml解析器。xml没有任何名称空间,因此不需要设置它 Private Function ParseWord(word As String) As String Dim tempFile As String tempFile = Environ("temp") & "\" & "temporaryWord" & ".xml"
Private Function ParseWord(word As String) As String
Dim tempFile As String
tempFile = Environ("temp") & "\" & "temporaryWord" & ".xml"
Call CreateFile(tempFile, word)
Dim xmlDoc As Object
Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")
With xmlDoc
.async = False
.setProperty "SelectionLanguage", "XPath"
.validateOnParse = False
.Load tempFile
'.setProperty "SelectionNamespaces", ""
'.Namespaces = False
End With
Dim xmlElement As Object
Set xmlElement = xmlDoc.DocumentElement
If xmlElement Is Nothing Then
MsgBox "error in element"
Exit Function
End If
Dim nodeXML As Object
Set nodeXML = xmlElement.SelectSingleNode("/definitions/definition/text")
If nodeXML Is Nothing Then
MsgBox "error"
Else
MsgBox nodeXML.Text
ParseWord = nodeXML.Text
End If
End Function
xml来源:
ahd legacy intransigent从字符串加载xml对我很有效。(可能是字符串编码问题?)
函数ParseWord(…)
的代码工作正常。但是函数CreateFile(…)
看起来怎么样?你能把这个代码也发出来吗?创建的文件需要使用UTF-8,xml文本中有一个特殊符号,该符号位于单词“Heritage”后的圆圈中。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><definitions><definition sequence="0"> <textProns/><sourceDictionary>ahd-legacy</sourceDictionary><exampleUses/><relatedWords/><labels/> <citations/><word>intransigent</word><attributionText>from The American Heritage® Dictionary of the English Language, 4th Edition</attributionText><text>Refusing to moderate a position, especially an extreme position; uncompromising.</text><partOfSpeech>adjective</partOfSpeech><score>0.0</score></definition></definitions>
Sub test()
'Cell A1 contains the xml
ParseXML (Range("A1"))
End Sub
Private Function ParseXML(xmlString As String) As String
Dim tempFile As String
Dim xmlDoc As Object
Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")
With xmlDoc
.async = False
.setProperty "SelectionLanguage", "XPath"
.validateOnParse = False
.LoadXML xmlString
'.setProperty "SelectionNamespaces", ""
'.Namespaces = False
End With
Dim xmlElement As Object
Set xmlElement = xmlDoc.DocumentElement
If xmlElement Is Nothing Then
MsgBox "error in element"
Exit Function
End If
Dim nodeXML As Object
Set nodeXML = xmlElement.SelectSingleNode("/definitions/definition/text")
If nodeXML Is Nothing Then
MsgBox "error"
Else
MsgBox nodeXML.Text
ParseXML = nodeXML.Text
End If
End Function