2014-12-03 70 views
2

我想要做的是將我的數據表導出到Excel的XML文檔。如何在具有相同值的另一個名稱空間時將名稱空間指定給XAttribute?

所以我需要的是這樣的:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<?mso-application Excel.Sheet?> 
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" />  

我使用System.Xml.Linq和我差不多有它,但我的代碼將不斷「SS」到工作簿的前面。這是我的代碼:

XDocument xmlssDoc2 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new 
    XProcessingInstruction("mso-application", "Excel.Sheet")); 

    XNamespace aw = "urn:schemas-microsoft-com:office:spreadsheet"; 
    XNamespace fc = "urn:schemas-microsoft-com:office:spreadsheet"; 
     XElement root = new XElement(aw + "Workbook", 
      new XAttribute("xmlns", "urn:schemas-microsoft-com:office:spreadsheet"), 
      new XAttribute(XNamespace.Xmlns + "ss", "urn:schemas-microsoft-com:office:spreadsheet") 
     );   

而結果我得到的是:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<?mso-application Excel.Sheet?> 
<ss:Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" />  

任何幫助,請!

回答

0

reference sourceXElement,它看起來好像命名空間/前綴屬性對以另外的順序推到push-down stack而寫,然後檢查對元素的命名空間,與從堆棧top to bottom - 有效地做以相反順序匹配添加屬性。

因此,如果你以相反的順序添加的命名空間中,ss省略:

 XDocument xmlssDoc2 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new 
     XProcessingInstruction("mso-application", "Excel.Sheet")); 

     XNamespace blank = "urn:schemas-microsoft-com:office:spreadsheet"; 
     XNamespace ss = "urn:schemas-microsoft-com:office:spreadsheet"; 

     XElement root = new XElementTest(blank + "Workbook"); 
     root.Add(new XAttribute(XNamespace.Xmlns + "ss", ss)); 
     root.Add(new XAttribute("xmlns", blank)); 

     Debug.WriteLine(root.ToString()); 

生產:

<Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns="urn:schemas-microsoft-com:office:spreadsheet" /> 

當然,這意味着xmlns屬性規格的命令具有根據XML規範,最好改爲should not matter

+1

好工作!我在前一天問過這個問題,實際上最終做了類似的事情,但你的答案是現成的!感謝dbc! – 2014-12-05 11:59:40

相關問題