我正在从excel 2013中创建一个xml文档,所以我使用vba来复制另一个xml文档。我在下面编写了一些代码来创建和保存我的xml文档。文档中的数据很好并且结构正确。然而,缺少两件事。我在我的项目中引用了Microsoft XML 3.0版。
缺少的第一行是来自xml文档,但是我想要复制的那一行是
<?xml version="1.0" encoding="utf-8" ?>
第二行也不同。我有,
-<MyXmlReport>
我试图复制的文件有,
-<MyXmlReport xmlns:xsi="http://www.w3.org/2001/XMLSchem-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema
以下是我的代码(目前仅用于测试)。我在创建DOMDocument时,上面的第一行会被添加到文档中吗?
更新
我添加了objDom.setProperty下面的行,当我使用getProperty(&#34; SelectionNamespaces&#34;)方法时,命名空间似乎就在那里但是当我打开文档时,我仍然看不到命名空间?
Public Sub CreateXMLDoc()
Dim objDom As DOMDocument
Dim objRootElem As IXMLDOMElement
Dim objMemElem As IXMLDOMElement
Set objDom = New DOMDocument
objDom.setProperty "SelectionNamespaces", "xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""" & " xmlns:xsd=""http://www.w3.org/2001/XMLSchema"""
' create the root element
Set objRootElem = objDom.createElement("MyXmlReport")
objDom.appendChild objRootElem
' create security element
Dim objSecElem As IXMLDOMElement
Set objSecElem = objDom.createElement("Security")
objRootElem.appendChild objSecElem
Dim str(1 To 3) As String
str(1) = "A"
str(2) = "B"
str(3) = "C"
For i = 1 To UBound(str)
Dim objProp As IXMLDOMElement
Set objProp = objDom.createElement(str(i))
objSecElem.appendChild objProp
objProp.Text = i
Next i
objDom.Save "C:\Somelocation\myFile.xml"
end sub
答案 0 :(得分:2)
您需要创建处理指令或XML声明。 Try this:
Dim declaration
Set declaration = objDom.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8' standalone='no' ")
objDom.appendChild declaration
答案 1 :(得分:2)
您需要将XML声明添加为处理指令(David已经涵盖了这一点):
Dim xmlDecl As IXMLDOMProcessingInstruction
Set xmlDecl = objDom.createProcessingInstruction("xml", "version=""1.0"" encoding=""utf-8""")
objDom.appendChild xmlDecl
命名空间声明是根元素的属性,因此您可以使用以下命令添加它们:
objRootElem.setAttribute "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"
objRootElem.setAttribute "xmlns:xsd", "http://www.w3.org/2001/XMLSchema"