Why am I getting the extra xmlns="" using LinqToXML?

Posted by Hcabnettek on Stack Overflow See other posts from Stack Overflow or by Hcabnettek
Published on 2010-05-27T15:36:47Z Indexed on 2010/05/27 18:11 UTC
Read the original article Hit count: 395

Filed under:
|
|
|
|

Hello all, I'm using LinqToXML to generate a piece of XML. Everything works great except I'm throwing in some empty namespace declarations somehow. Does anyone out there know what I'm doing incorrectly? Here is my code

     private string SerializeInventory(IEnumerable<InventoryInformation> inventory)
    {
        var zones = inventory.Select(c => new {
            c.ZoneId
            , c.ZoneName
            , c.Direction
        }).Distinct();

        XNamespace ns = "http://www.dummy-tmdd-address";
        XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

        var xml = new XElement(ns + "InventoryList"
                               , new XAttribute(XNamespace.Xmlns + "xsi", xsi)
                               , zones.Select(station => new XElement("StationInventory"
                                     , new XElement("station-id", station.ZoneId)
                                     , new XElement("station-name", station.ZoneName)
                                     , new XElement("station-travel-direction", station.Direction)
                                     , new XElement("detector-list"
                                        , inventory.Where(p => p.ZoneId == station.ZoneId).Select(plaza =>
                                         new XElement("detector"
                                            , new XElement("detector-id", plaza.PlazaId)))))));

        xml.Save(@"c:\tmpXml\myXmlDoc.xml");
        return xml.ToString();
    }

And here is the resulting xml. I hope it renders correctly? The browser may hide the tags.

- <InventoryList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xmlns="http://www.dummy-tmdd-address">
<StationInventory xmlns="">
  <station-id>999</station-id> 
  <station-name>Zone 999-SEB</station-name> 
  <station-travel-direction>SEB</station-travel-direction> 
 <detector-list>
<detector>
  <detector-id>7503</detector-id> 
 </detector>
<detector>
  <detector-id>2705</detector-id> 
 </detector>
</detector-list>
  </StationInventory>
  </InventoryList>

Notice the empty namespace declaration in the first child element. Any ideas how I can remedy this? Any tips are of course appreciated.

Thanks All, ~ck

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml