1

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 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

2 Comments

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: 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 =)
0

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";

5 Comments

-1: Anthony, I don't believe this will emit the namespace declarations.
@John: actually, it does; nsmgr.LookupNamespace() method returns a string, so this code is pretty equals mine
@John: did you try it first? I did.
@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: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.