This may be a beginner xml question, but how can I generate an xml document that looks like the following?
Try this code:
string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName);
string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);`
I hope you will get some useful information from this thread - XElement default namespace on attributes provides unexpected behaviour
EDIT:
Another FAQ at - http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/c0648840-e389-49be-a3d2-4d5db17b8ffffd
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"));
}
}
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">
<ci:field1>test</ci:field1>
<ca:field2>another test</ca:field2>
</root>
For XmlDocument it's similar:
XmlAttribute attribute1 = sessionXml.CreateAttribute("s", "Attribute1", namespaceURI);
XmlAttribute attribute2 = sessionXml.CreateAttribute("s", "Attribute2", namespaceURI);
XmlAttribute attribute3 = sessionXml.CreateAttribute("s", "Attribute3", namespaceURI);
XmlAttribute attribute4 = sessionXml.CreateAttribute("s", "Attribute4", namespaceURI);