perfectxml.com
 Basic Search  Advanced Search   
Topics Resources Free Library Software XML News About Us
home » focus » msxml » ask a question » past questions & answers Friday, 12 October 2007
 
NEWS
MSXML 4.0 SP2 now available!

 
MSXML
Basics
DOM
SAX
XPath
XSLT
Schemas
SOM
HTTP Access
.NET
Data Islands
Ask a Question
   Past Q&As
C++ Samples
DLL/Version Info
Reference Guide
Books
KB Articles
   HOW TO
   SAMPLE
   INFO
   BUG/PRB
   FIX
   Misc.
MSXML Tips
   August 2002
   September 2002
MSXML Tools

Microsoft XML Core Services


Go back to list of previously asked questions and answers

Question: I am trying to use the createNode method, but am not able to figure out how to assign multiple namespaces to an element/node??
Asked By: Harish
Viewed: 2171
Answer: At a time, a node can be in a single namespace. Another important fact to remember is that MSXML is "namespace-enabled" - that means it will automatically figure out when and where to add the namespace declarations based on how you are creating the nodes.

Consider the following Visual Basic code that uses MSXML 4.0

Dim objXMLDOMDoc As New MSXML2.DOMDocument40
Dim objRootNode As IXMLDOMNode
Dim objChildNode As IXMLDOMNode
Dim objAttribNode As IXMLDOMNode

objXMLDOMDoc.async = False
objXMLDOMDoc.validateOnParse = False

'Creating the root element
Set objRootNode = objXMLDOMDoc.createNode(NODE_ELEMENT, "ns1:RootNode", "http://Namespace1")
Set objXMLDOMDoc.documentElement = objRootNode

'First child under the root element (different namespace)
Set objChildNode = objXMLDOMDoc.createNode(NODE_ELEMENT, "ns2:ChildNode", "http://Namespace2")
objRootNode.appendChild objChildNode

'Attribute to the root namespace (another namespace)
Set objAttribNode = objXMLDOMDoc.createNode(NODE_ATTRIBUTE, "ns3:Attribute1", "http://AttribNamespace")
objAttribNode.nodeTypedValue = "Attribute Value"
objRootNode.Attributes.setNamedItem objAttribNode

MsgBox objXMLDOMDoc.xml

Step through the above code carefully, and you'll see that it is a very simple code that first creates a root element (in http://Namespace1 namespace), then it creates a child node (with http://Namespace2 as the namespace) under the root element; and finally we create an attribute (with http://AttribNamespace namespace) and associate it with the root element. The above code generates the following XML:

<ns1:RootNode 
        xmlns:ns1="http://Namespace1" 
        xmlns:ns3="http://AttribNamespace" 
        ns3:Attribute1="Attribute Value">

        <ns2:ChildNode xmlns:ns2="http://Namespace2"/>

</ns1:RootNode>
Note how MSXML decided to put the namespace declarations.


Go back to list of previously asked questions and answers
  Contact Us |  | Site Guide | About PerfectXML | Advertise ©2004 perfectxml.com. All rights reserved. | Privacy