Add new namespaces to an existing XmlDocument

I am writing a translator for a vertical market application. The old format is a CSV variant, the new format is XML. For the most part it's working very well.

The old format is well defined with about 70+ "tables". The new format has a rich schema defined to provide for validation, something the old format couldn't handle very well.

The old format includes the capability of specifying "user defined tables", and I can successfully translate them, including writing a custom schema for each UDT. The process that I'm using is to populate a dataset with the CSV data, use WriteXml to a temp file and append each custom table as I encounter it, reload the custom table data at end of the conversion into another DS, and use WriteXmlSchema to generate a default schema for the combined custom tables. So far, that seems to work pretty well.

The problem is that I need to add some additional attributes to the root tag specifying some additional namespaces for the geotech industry. It seems straight forward to try something like

dim oXmlDoc as XmlDocument = new blah blah
dim oAttrib as XmlAttribute = oXmlDoc.CreateAttribute("xmlns:gml", "http://www.opengis.net/gml")
oXmlDoc.DocumentElement.AppendChild(oAttrib)
oXmlDoc.Save(schemaFileName)

Unfortunately, this fails on the save with an error


The namespace declaration attribute has an incorrect URI: "..."

What am I doing wrong?

Thanks!

Sean

[1610 byte] By [sean_kirkpatrick] at [2007-12-25]
# 1

This code should work:

XmlDocument xmlDoc;

XmlAttributeCollection docAttribs = objSomeElement.Attributes;

XmlNode objNewNode = xmlDoc.CreateNode(XmlNodeType.Attribute,

"xmlns", attrName, "http://www.w3.org/2000/xmlns/");

objNewNode.Value = "SomeNamespace U R I";

docAttribs.Append((XmlAttribute)objNewNode);

Cheers,
Dimitre Novatchev

Dimitre_Novatchev at 2007-9-3 > top of Msdn Tech,.NET Development,XML and the .NET Framework...
# 2

Right on, Dimitre, that did the trick. Thanks a bunch.

For reference, here's my code:

Sean

' load the DataSet generated schema
oXmlDoc.Load(_sSchemaFile)

' get rid of unneeded attributes
oXmlDoc.DocumentElement.RemoveAttribute(
"xmlns:msdata")
oXmlDoc.DocumentElement.RemoveAttribute(
"xmlns")

' Dimitre's suggested code translated to VB
Dim
oAttrColl As Xml.XmlAttributeCollection = oXmlDoc.DocumentElement.Attributes

Dim oNode As Xml.XmlNode = oXmlDoc.CreateNode(Xml.XmlNodeType.Attribute, "xmlns", "gml", "http://www.w3.org/2000/xmlns/")

oNode.Value = "http://www.opengis.net/gml"

oAttrColl.Append(DirectCast(oNode, Xml.XmlAttribute))

oXmlDoc.Save(_sSchemaFile)

sean_kirkpatrick at 2007-9-3 > top of Msdn Tech,.NET Development,XML and the .NET Framework...

.NET Development

Site Classified