Home > Net >  How to add xml and xml-stylesheet nodes to an XML file in VBA?
How to add xml and xml-stylesheet nodes to an XML file in VBA?

Time:01-18

I'm using Access VBA to create an XML file.

Dim dDokument As MSXML2.DOMDocument60
Set dDokument = New MSXML2.DOMDocument60

Dim environmentalDataNode As IXMLDOMElement
Set environmentalDataNode = dDokument.createElement("mainnode")

'...Adding some stuff

Call dDokument.save("c:\Temp\test.xml") 

This writes a fine XML file, except I have to have these two lines at the beginning of my XML.

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="https://secure.umweltbundesamt.at/h2o/xml/uba_schnittstellen.xslt"?>

They are not written when I use the code above.

So, how do I add XML and xml-stylesheet nodes to my DOMDocument60?

CodePudding user response:

<?xml-stylesheet type="text/xsl" href="https://secure.umweltbundesamt.at/h2o/xml/uba_schnittstellen.xslt"?> is a processing instruction you can create with e.g. Set pi = dDokument.createProcessingInstruction("xml-stylesheet", "type=""text/xsl"" href=""https://secure.umweltbundesamt.at/h2o/xml/uba_schnittstellen.xslt""") (I hope I have the correct VB syntax for escaping the double quotes and the assigment) and then insert with e.g. dDokument.insertBefore(pi, dDocument.documentElement).

The first item you have shown is the XML declaration. It is usually not created with DOM methods as a node but rather added during serialization/saving of the document tree, like done by the save method. Don't you get an XML declaration added (with the default encoding UTF-8) by your use of save() at the end?

https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms755439(v=vs.85) suggests that the XML declaration, though technically not being a processing instruction, in the context of the MSXML APIs, can nevertheless be created with Set dec = dDocument.createProcessingInstruction("xml", "version=""1.0"" encoding=""UTF-8""") (and of course be inserted with dDocument.insertBefore(dec, dDocument.firstChild)).

  •  Tags:  
  • Related