c# - Creating XElement with namespaces? -


i trying following xml (for 3rd party; needs exact) , having trouble xmlns on inner elements:

<headerresponse xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema">   <sessionid xmlns="http://www.example.com/portal-api">4654654564</sessionid>   <uniquetranid xmlns="http://www.example.com/portal-api">gh0000000</uniquetranid>   <statuscode xmlns="http://www.example.com/portal-api">1</statuscode>   <statuscodedescription xmlns="http://www.example.com/portal-api">jhkjhkjhkjhkjkjhkjkkjhkhk</statuscodedescription>   <message xmlns="http://www.example.com/portal-api">testmessage</message> </headerresponse> 

from other examples, have got following:

xnamespace xsi = "http://www.w3.org/2001/xmlschema-instance"; xnamespace xsd = "http://www.w3.org/2001/xmlschema"; xnamespace api = "http://www.example.com/portal-api";  xelement example = new xelement("headerresponse",   new xattribute(xnamespace.xmlns + "xsi", xsi),   new xattribute(xnamespace.xmlns + "xsd", xsd),   new xelement("sessionid", "some session id", new xattribute("xmlns", api)) ); 

without sessionid, happily created main headerresponse xsi , xsd, when added sessionid in , try post contents in immediate window example.tostring(), following error:

the prefix '' cannot redefined '' 'http://www.example.com/portal-api' within same start element tag. 

you need define element name sessionid qualified name (i.e. including namespace). insertion of default namespace declaration handled automatically linq xml:

xnamespace xsi = "http://www.w3.org/2001/xmlschema-instance"; xnamespace xsd = "http://www.w3.org/2001/xmlschema"; xnamespace api = "http://www.example.com/portal-api";  xelement example = new xelement("headerresponse",     new xattribute(xnamespace.xmlns + "xsi", xsi),     new xattribute(xnamespace.xmlns + "xsd", xsd),     new xelement(api + "sessionid", "some session id") );    

you can control declarations adding them you've done. example, add declaration api prefix root simplify result:

xelement example = new xelement("headerresponse",     new xattribute(xnamespace.xmlns + "xsi", xsi),     new xattribute(xnamespace.xmlns + "xsd", xsd),     new xattribute(xnamespace.xmlns + "api", api),     new xelement(api + "sessionid", "some session id") );    

note although xml different required xml, there semantically no difference between them.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -