0

The following LINQ to XML C# code creates one XElement having one XAttribute:

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

It generates an inline namespace producing the following XML element having p1:

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

However what I really want is this:

<Worksheet ss:Name="Sheet1" />

How can I get the second form of the element?

Note: If you recognize the XML structure, I'm filling out an Excel spreadsheet but this is anecdotal to the question.

Ultimately I'm creating the Worksheet element in the following Excel document:

<?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>
John K
  • 28,441
  • 31
  • 139
  • 229

1 Answers1

1

I had to define my XML ss namespace as an XNamespace instance i.e.:

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

and then concatenate the namespace instance with the attribute name like so:

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

Produces desired ss:Name XML attribute:

<Worksheet ss:Name="Sheet1" 
John K
  • 28,441
  • 31
  • 139
  • 229
  • You've tried this, and you get `ss` as the prefix? I'm surprised that you don't have to declare the namespace in order to get the prefix set. Something like in http://msdn.microsoft.com/en-us/library/system.xml.linq.xattribute.isnamespacedeclaration.aspx – John Saunders Jan 09 '12 at 22:31
  • Thanks for the link; I hadn't tried `.IsNamespaceDeclaration` The code above is copied and pasted along with result, except the worksheet name string which I changed to be generic "Sheet1". But the `ss` namespace is declared in the larger XML document that I pasted at the bottom of my question. – John K Jan 10 '12 at 02:49