How can I write xml with a namespace and prefix with XElement?
Solution 1:
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"));
}
}
Solution 2:
Try this code:
string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName);
string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);`