Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a namespace prefix to an XAttribute in .NET?

Tags:

c#

.net

soap

xml

All, I want to create a soap envelope xml document eg.

<soap:Envelope soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding" xmlns:soap="http://www.w3.org/2001/12/soap-envelope"></soap:Envelope>

I am using System.Xml.Linq to do this but I cannot figure out how to add the soap prefix to the encodingStyle attribute.

So far, I have this:

XNamespace ns = XNamespace.Get("http://www.w3.org/2001/12/soap-envelope");
XAttribute prefix = new XAttribute(XNamespace.Xmlns + "soap", ns);
XAttribute encoding = new XAttribute("encodingStyle", "http://www.w3.org/2001/12/soap-encoding");

XElement envelope = new XElement(ns + "Envelope", prefix, encoding);

which gives me

<soap:Envelope encodingStyle="http://www.w3.org/2001/12/soap-encoding" xmlns:soap="http://www.w3.org/2001/12/soap-envelope"></soap:Envelope>

You use XAttribute to add a prefix to an element, can I use XAttribute to add a prefix to an XAttribute??!

thanks, P

like image 232
Peter Goras Avatar asked Dec 10 '10 06:12

Peter Goras


1 Answers

Specify the namespace when you create the 'encodingStyle' XAttribute (by using ns + "encodingStyle"):

XAttribute encoding = new XAttribute(ns + "encodingStyle", "http://www.w3.org/2001/12/soap-encoding");

The two-parameter XAttribute constructor takes an XName as the first argument. This can either be constructed implicitly from a string (as in the code in your question), or directly by "adding" a string to an XNamespace to create an XName (as above).

like image 165
Bradley Grainger Avatar answered Oct 08 '22 03:10

Bradley Grainger