tags:

views:

99

answers:

2

I am struggling to output the following XML using the XmlDocument object in .NET. Any suggestions?

This is what I would like to output...

<l:config
    xmlns:l="urn:LonminFRConfig"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:LonminFRConfig lonminFRConfigSchema.xsd">

</l:config>

The namespaces are really giving me a hard time!

+2  A: 

Try this:

XmlDocument xmlDoc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("l", "urn:LonminFRConfig");
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

XmlElement config = xmlDoc.CreateElement("l:config", nsmgr.LookupNamespace("l"));
XmlAttribute schemaLocation = xmlDoc.CreateAttribute(
    "xsi:schemaLocation", nsmgr.LookupNamespace("xsi"));
config.Attributes.Append(schemaLocation);
schemaLocation.Value = "urn:LonminFRConfig lonminFRConfigSchema.xsd";

xmlDoc.AppendChild(config);
xmlDoc.Save(Console.Out);

Good luck!

Rubens Farias
LookupNamespace is quite expensive when you need to create a lot of elements especially when creating from scratch where you already know all the aliases and namespaces you want to use.
AnthonyWJones
@AnthonyWJones: ty for your info! I just read LookupNamespace implementation through reflector and saw it uses a Dictionary<> internally, so this is fast, but not faster than const string, of course =)
Rubens Farias
That works like a charm, thanks Rubens!
willem
A: 

Thi will do it.

const string lNS = "urn:lLominFRConfig";
const string xsiNS = "http://www.w3.org/2001/XMLSchema-instance";

var dom = new XmlDocument();

var configElem = dom.AppendChild(dom.CreateElement("l:config", lNS));

configElem.Attributes.Append(dom.CreateAttribute("xsi:schemaLocation", xsiNS))
    .Value = "urn:LonminFRConfig lonminFRConfigSchema.xsd";
AnthonyWJones
-1: Anthony, I don't believe this will emit the namespace declarations.
John Saunders
@John: actually, it does; nsmgr.LookupNamespace() method returns a string, so this code is pretty equals mine
Rubens Farias
@John: did you try it first? I did.
AnthonyWJones
@John: actually, when you run the code and fix the obvious typo (missing ";" on the `var configElem = ....` line), it does output the result as required by the question.
marc_s
@marc: good catch, originally configElem wasn't in my tested code it was all one line but I felt it just needed breaking up a bit once I had posted the answer.
AnthonyWJones
@Anthony: sorry, misread the code. -1 removed.
John Saunders
Thanks for the effort guys :)
willem