How can I write xml with a namespace and prefix with XElement?

Chris Conway picture Chris Conway · Aug 27, 2009 · Viewed 21.4k times · Source

This may be a beginner xml question, but how can I generate an xml document that looks like the following?

<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
    <ci:field1>test</ci:field1>
    <ca:field2>another test</ca:field2>
</root>

If I can get this to be written, I can get the rest of my problem to work.

Ideally, I'd like to use LINQ to XML (XElement, XNamespace, etc.) with c#, but if this can be accomplished easier/better with XmlDocuments and XmlElements, I'd go with that.

Thanks!!!

Answer

Andrew Hare picture Andrew Hare · Aug 27, 2009

Here is a small example that creates the output you want:

using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        XNamespace ci = "http://somewhere.com";
        XNamespace ca = "http://somewhereelse.com";

        XElement element = new XElement("root",
            new XAttribute(XNamespace.Xmlns + "ci", ci),
            new XAttribute(XNamespace.Xmlns + "ca", ca),
                new XElement(ci + "field1", "test"),
                new XElement(ca + "field2", "another test"));
    }
}