Sowvik Roy Sowvik Roy - 4 months ago 35
C# Question

Generate XML with multiple namespaces using XDocument

I have XML like this:

<stream:stream to="" from="" xml:lang="en" xmlns="jabber:client" xmlns:stream="" version="1.0"/>

Try to generate the XML using
like this

private readonly XNamespace _streamNamespace = "";
private readonly XName _stream;

_stream = _streamNamespace + "stream";

XDocument xdoc=new XDocument(
new XElement(_stream,
new XAttribute("from", ""),
new XAttribute("to",""),
new XAttribute("xmlns:stream",""),
new XAttribute("version","1.0"),
new XAttribute("xml:lang","en")

But I get an exception:

Additional information: The ':' character, hexadecimal value 0x3A, cannot be included in a name.


To add namespace declaration you can use XNamespace.Xmlns, and to reference the predefined namespace prefix xml use XNamespace.Xml, for example :

XNamespace stream = "";
var result = new XElement(stream + "stream",
                    new XAttribute("from", ""),
                    new XAttribute("to",""),
                    new XAttribute(XNamespace.Xmlns + "stream", stream),
                    new XAttribute("version","1.0"),
                    new XAttribute(XNamespace.Xml+"lang","en"),
//above prints :
//<stream:stream from="" to="" 
//               xmlns:stream="" version="1.0" 
//               xml:lang="en">