Home  >  Article  >  Backend Development  >  Detailed introduction on how to use DOM to create XML

Detailed introduction on how to use DOM to create XML

黄舟
黄舟Original
2017-03-07 16:38:251249browse

When I introduced XML and asked others to try using DOM, more than one person asked me whether DOM can be used to directly generate an XML file out of thin air.

Of course, this is certainly possible. The second step is how to write the program.

Then I will talk about this issue specifically in this article using an example of DOM implementation of the COM interface of VB and MSXML:

First of all, what I want to explain is that I use The version of MSXML is included with IE5, and the version number is 5.0.2919.3800. The interface of Microsoft's early version is somewhat different from the new one, so when programming by yourself, you should take a look at its interface and instructions.

If you are not familiar with VB and COM, it may be difficult to read the following, but VB should be simpler and clearer than other language implementations.

First declare the variables of several objects to be used below:

Dim tempdoc As MSXML.DOMDocument
Dim tempnode As MSXML.IXMLDOMNode 
Dim tempelement As MSXML.IXMLDOMElement 
Dim tempattribute As MSXML.IXMLDOMElement 
Dim root As MSXML.IXMLDOMElement

Generate an XML DOMDocument object

Set tempdoc = New MSXML.DOMDocument

Generate the root node and set it as the root of the file

Set root = tempdoc.createElement("MyRoot") 
Set tempdoc.documentElement = root

Generate a child node and add it to the root node, and set an attribute for this node

Set tempnode = tempdoc.createNode(MSXML.NODE_ELEMENT, "MyNode", "") 
tempnode.Text = "MyNodeValue" 
root.appendChild tempnode

Obtain the interface of the element node and add the attribute

Set tempelement = tempnode 
tempelement.setAttribute "MyAttribute", "MyAttributeValue"

Write an xml file

Open "MyXMLFile.xml" for output as #1 
PRint #1, root.XML 
Close #1

The following is the content of the XML file generated by the above program:

   MyNodeValue

There are also non-DOM interfaces available in MSXML, it depends on your own usage.

The above is a detailed introduction on how to use DOM to create XML. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn