Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XElement is automatically adding xmlns="" to itself

Tags:

I am creating a new XDocument from a table. I have to validate the document from an XSD document and it keeps failing because it add the xmlns="" to one of the Elements when it shouldn't. Here's parts of the code that are pertinent.

    XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";                 XNamespace xmlns = "https://uidataexchange.org/schemas";                 XElement EmployerTPASeparationResponse = null;                 XElement EmployerTPASeparationResponseCollection = new XElement(xmlns + "EmployerTPASeparationResponseCollection", new XAttribute(XNamespace.Xmlns + "xsi", xsi), new XAttribute(xsi + "schemaLocation", "https://uidataexchange.org/schemas SeparationResponse.xsd"));                 XDocument doc = new XDocument(                 new XDeclaration("1.0", null, "yes"), EmployerTPASeparationResponseCollection);     //sample XElement populate Element from database     StateRequestRecordGUID = new XElement("StateRequestRecordGUID");                         StateRequestRecordGUID.SetValue(rdr["StateRequestRecordGUID"].ToString());      //sample to add Elements to EmployerTPASeparationResponse     EmployerTPASeparationResponse = new XElement("EmployerTPASeparationResponse");                     if (StateRequestRecordGUID != null)                     {                         EmployerTPASeparationResponse.Add(StateRequestRecordGUID);                     }      //the part where I add the EmployerTPASeparationResponse collection to the parent     EmployerTPASeparationResponseCollection.Add(EmployerTPASeparationResponse); 

The above code produces the following xml file.

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <EmployerTPASeparationResponseCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://uidataexchange.org/schemas SeparationResponse.xsd" xmlns="https://uidataexchange.org/schemas"> <EmployerTPASeparationResponse xmlns="">     <StateRequestRecordGUID>94321098761987654321323456109883</StateRequestRecordGUID>   </EmployerTPASeparationResponse> </EmployerTPASeparationResponseCollection> 

Notice the element EmployerTPASeparationResponse. It has an empty xmlns attribute. What I want to happen is to just write EmployerTPASeparationResponse with no attributes at all.

like image 484
Zach Avatar asked May 10 '11 20:05

Zach


1 Answers

You need to specify the namespace of the elements you are adding. e.g.

//sample XElement populate Element from database StateRequestRecordGUID = new XElement(xmlns + "StateRequestRecordGUID"); 

and

//sample to add Elements to EmployerTPASeparationResponse EmployerTPASeparationResponse = new XElement(xmlns + "EmployerTPASeparationResponse"); 
like image 54
Dustin Hodges Avatar answered Sep 25 '22 01:09

Dustin Hodges