【发布时间】:2015-05-18 09:38:20
【问题描述】:
目前我正在创建这样的 XML - 而且效果很好......
Private Function CreateDom()
Dim dom
Set dom = New DOMDocument
dom.async = False
dom.validateOnParse = False
dom.resolveExternals = False
dom.preserveWhiteSpace = True
Set CreateDom = dom
End Function
Public Function generateXML(sourceFileLocation)
'I make an instance of the dom
Set dom = CreateDom
'This is how I setup a root node
Set rootXML= dom.createElement("root")
dom.appendChild rootXML
'This is how I set attributes
questestinterop.setAttribute "attributeName", "attributeValue"
'setup a child node
Set childOfRoot = dom.createElement("childOfRoot")
rootXML.appendChild childOfRoot
'This is how I set the text of the element
childOfRoot.Text = "Text Value"
End Function
这在我上面的基本示例中没问题,但是可以说我要创建更多的 XML - 我最终得到了 LOADS 的 appendchilds 和很多对象 - 这接缝效率低且容易出错 - 但有优势我可以随时将一个对象添加到以前创建的对象中。
对于 MSXML,我没有可用的 InnerXML,因此代码很冗长。我正在寻找一种使用 MSXML 和 VBA/VB 来创建 XML 的更有效的方法——或者这种工作的最佳实践——我不禁觉得有更好的方法。
更新 我在上面提到没有 InnerXML - 但是有一种方法可以将 XML sn-p 加载到 DOM 中
Sub MergeXML()
'Define
Dim oXml As New MSXML2.DOMDocument
Dim oXml2 As New MSXML2.DOMDocument
'Assign
oXml.loadXML ("<SomeRootElement><Input></Input></SomeRootElement>")
oXml2.loadXML ("<Output><SomeElement></SomeElement></Output>")
'or assign via file
'oXml.Load("c:\Xml.xml")
'oXml2.Load("c:\Xml2.xml")
'Process
oXml.FirstChild.appendChild oXml2.selectSingleNode("//Output")
'Destroy
oXml.Save ("c:\NewXml.xml")
Set oXml2 = Nothing
Set oXml = Nothing
End Sub
来源:http://p2p.wrox.com/beginning-vb-6/28319-xml-using-msxml2-domdocument-object.html
【问题讨论】:
-
此代码来自 VBA,但仍可在 VB.net 中使用 - MSXML 方法保持不变
-
使用如下网页的序列化类:stackoverflow.com/questions/30274147/…
-
Set在 VB.Net 中仍然有效吗?另外,将Option Strict On添加到代码文件的顶部或在项目的属性中设置它。 -
有许多 VB.NET 解决方案在 VBA 中不起作用。对一个人来说是最佳的,对另一个人来说可能不是这样。如果您不追求 .NET 解决方案,请删除标签。