views:

407

answers:

3

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"&gt;
    <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!!!

+4  A: 

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"));
    }
}
Andrew Hare
A: 
XNamespace ci = "http://somewhere.com";
XNamespace ca = "http://somewhereelse.com";
XElement root = new XElement(aw + "root",
    new XAttribute(XNamespace.Xmlns + "ci", "http://somewhere.com"),
    new XAttribute(XNamespace.Xmlns + "ca", "http://somewhereelse.com"),
    new XElement(ci + "field1", "test"),
    new XElement(ca + "field2", "another test")
);
Console.WriteLine(root);

This should output

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