Kirk Evans Blog

.NET From a Markup Perspective

Namespaces in XML

Antonio asks:

I have to create this same structure using the DOM model. How do I create the namespace attributes?

<manifest identifier=”MANIFEST1 xmlns:imsmd=” xsi:schemaLocation=” imscp_v1p1p3.xsd imsmd_v1p2p2.xsd xmlns:xsi=” xmlns=” />

The problem in Antonio’s case is the unused “imsmd” namespace prefix. This example shows how to create a namespace prefix as an attribute, how to create an attribute bound to a namespace, and how the namespace declaration is automatically generated based on a specified namespace prefix and namespace URI (notice how the xsi:schemaLocation attribute is created in this example):

XmlDocument doc = new XmlDocument();
XmlNode root = doc.AppendChild(doc.CreateElement(“manifest”,”″));
XmlAttribute attrib = doc.CreateAttribute(“identifier”);
attrib.Value = “MANIFEST1”;
attrib = doc.CreateAttribute(“xmlns:imsmd”);
attrib.Value = “”;
attrib = doc.CreateAttribute(“xsi”,”schemaLocation”,””);
attrib.Value = “ imscp_v1p1p3.xsd imsmd_v1p2p2.xsd”;
doc.WriteContentTo(new XmlTextWriter(Response.Output));