临时写了下,大致是这样: Sub Main() Dim xmldoc As DOMDocument Dim values_node As IXMLDOMNode Dim RssNode As IXMLDOMNode Set xmldoc = New DOMDocument Set pi = xmldoc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'") xmldoc.appendChild pi Set RssNode = xmldoc.CreateNode(NODE_ELEMENT, "rss", "") xmldoc.appendChild RssNode Set values_node = xmldoc.createElement("test") RssNode.appendChild values_node CreateNode values_node, "Value", "测/试/行" xmldoc.save m_AppPath & "test.xml" Set xmldoc = Nothing End Sub Private Sub CreateNode(ByVal parent As IXMLDOMNode, ByVal node_name As String, ByVal node_value As String) Dim new_node As IXMLDOMNode Set new_node = parent.ownerDocument.createElement(node_name) new_node.Text = node_value parent.appendChild new_node End Sub
Sub Main() ... 'xmldoc.save m_AppPath & "test.xml" SaveWithEncoding xmldoc, m_AppPath & "test.xml", "UTF-8" ... End Sub
Private Sub SaveWithEncoding(ByVal xmldoc As DOMDocument, _ ByVal FileName As String, _ ByVal Encoding As String) Dim s As ADODB.Stream Set s = New ADODB.Stream With s .Open .Type = adTypeText .Charset = Encoding
给个简单的出错例子。
Dim xmldoc As DOMDocument
Dim values_node As IXMLDOMNode
Dim RssNode As IXMLDOMNode
Set xmldoc = New DOMDocument
Set pi = xmldoc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'")
xmldoc.appendChild pi
Set RssNode = xmldoc.CreateNode(NODE_ELEMENT, "rss", "")
xmldoc.appendChild RssNode
Set values_node = xmldoc.createElement("test")
RssNode.appendChild values_node
CreateNode values_node, "Value", "测/试/行"
xmldoc.save m_AppPath & "test.xml"
Set xmldoc = Nothing
End Sub
Private Sub CreateNode(ByVal parent As IXMLDOMNode, ByVal node_name As String, ByVal node_value As String)
Dim new_node As IXMLDOMNode
Set new_node = parent.ownerDocument.createElement(node_name)
new_node.Text = node_value
parent.appendChild new_node
End Sub
...
'xmldoc.save m_AppPath & "test.xml"
SaveWithEncoding xmldoc, m_AppPath & "test.xml", "UTF-8"
...
End Sub
Private Sub SaveWithEncoding(ByVal xmldoc As DOMDocument, _
ByVal FileName As String, _
ByVal Encoding As String)
Dim s As ADODB.Stream
Set s = New ADODB.Stream
With s
.Open
.Type = adTypeText
.Charset = Encoding
xmldoc.save s
.SaveToFile FileName
.Close
End With
End Sub
用纯字符串处理不仅有编码问题、还有字符转义问题。