2010-05-27 31 views
2

我使用LINQ to XML來生成一段XML。除了我以某種方式拋出一些空的名稱空間聲明之外,一切都很好。有沒有人知道我做錯了什麼?這裏是我的代碼爲什麼我使用LINQ to XML獲得額外的xmlns =「」?

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(); 
    } 

這裏是結果xml。我希望它正確渲染?瀏覽器可能會隱藏標籤。

<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> 

公告中的第一個子元素的空命名空間聲明。任何想法如何我可以補救這個?任何提示,當然讚賞。

謝謝大家。

回答

2

由於缺少命名空間:

new XElement("StationInventory"... 

這含蓄地表明空命名空間「」爲StationInvetory元素。你應該這樣做:

new XElement(ns + "StationInventory"... 

注意,你必須爲你創建一個生活在ns命名空間中的任何元素做到這一點。根據範圍,XML序列化程序將確保使用正確的名稱空間前綴限定元素。

相關問題