2012-01-09 26 views
0

以下LINQ到XML C#代碼創建具有一個XAttribute一個XElement不需要的內聯的命名空間格式

XElement xWorksheet = 
    new XElement("Worksheet", new XAttribute(XName.Get("Name", "ss"), "Sheet1")); 

它產生一個內聯的命名空間產生以下XML元素具有P1:

<Worksheet p1:Name="Sheet1" xmlns:p1="ss" /> 

但是我真正想要的是這樣的:

<Worksheet ss:Name="Sheet1" /> 

如何獲取元素的第二種形式?

注:如果你認識到XML結構,我填寫的Excel電子表格,但是這是傳聞的問題。

最終我下面的Excel文檔中創建的工作表元素:

<?xml version="1.0"?> 
<?mso-application progid="Excel.Sheet"?> 
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" 
xmlns:o="urn:schemas-microsoft-com:office:office" 
xmlns:x="urn:schemas-microsoft-com:office:excel" 
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" 
xmlns:html="http://www.w3.org/TR/REC-html40"> 

    <Worksheet ss:Name="Sheet1"> 
    <Table> 
     <Row> 
     <Cell> 
      <Data ss:Type="String">number </Data> 
     </Cell> 
     <Cell> 
      <Data ss:Type="String">name </Data> 
     </Cell> 
     </Row> 
    </Table> 
    </Worksheet> 

</Workbook> 

回答

1

我不得不定義我的XML命名空間SS作爲XNamespace實例即:

XNamespace ss = XNamespace.Get("urn:schemas-microsoft-com:office:spreadsheet"); 
// Note: The string value doesn't seem to matter in my case. 

,然後串聯與屬性名稱,像這樣的命名實例:

// Broken out into two steps for clarity. 
XAttribute a = new XAttribute(ss + "Name", "Sheet1"); 
// Put attribute on element: 
xWorksheet = new XElement("Worksheet", a); 

產生具有所需SS:名稱 XML屬性:

<Worksheet ss:Name="Sheet1" 
+0

你已經試過這,你會得到'ss'爲前綴?我很驚訝你不必爲了獲得前綴集而聲明命名空間。喜歡的東西在http://msdn.microsoft.com/en-us/library/system.xml.linq.xattribute.isnamespacedeclaration.aspx – 2012-01-09 22:31:22

+0

感謝您的鏈接;我沒有試過'.IsNamespaceDeclaration'上面的代碼被複制並粘貼到結果中,除了工作表名稱字符串,我改爲通用的「Sheet1」。但'ss'命名空間是在我的問題底部粘貼的較大的XML文檔中聲明的。 – 2012-01-10 02:49:59