4

Trying to edit an XML document that uses Excels XML-Namespaces:

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

I need to get to this result (need the ss: prefix befire Type):

<Cell ...><Data ss:Type="String">value</Data></Cell>

I've looked over the question Unable add namespace with PHPs SimpleXML but this method is not helping here. In other words, running this as outlined there

$data = $cells[$i]->addChild('Data','value'); 
$data->addAttribute("ss:Type","String","urn:schemas-microsoft-com:office:spreadsheet");

gives me

<Cell ...><Data Type="String">value</Data></Cell>

without the ss: prefix. And if I remove the urn: prefix, then I'm getting this

<Cell ...><Data xmlns:ss="schemas-microsoft-com:office:spreadsheet" ss:Type="String">value</Data></Cell>

In either case, when I open the document with Excel, the data is invisible. With urn: the ss: is missing and without urn: the definition becomes part of the element which is not working in Excel.

Community
  • 1
  • 1
user988201
  • 161
  • 1
  • 6
  • I am trying to do the same in java. Can you please help?
    http://stackoverflow.com/questions/11025799/add-namespace-to-java-dom-attribute
    – U-L Jun 14 '12 at 18:00

1 Answers1

12

If you want to add an attribute with a specific namespace prefix w/o adding the namespace to the document, you have to specify not only the prefix in the name parameter, but also prefix it again with xmlns, in my example: xmlns:ss:Type. The namespace URI (third parameter) then will be ignored as well, so it is not necessary either:

$data->addAttribute("xmlns:ss:Type", "String");

Note the xmlns: in front of ss:Type. The output then is as required:

<Cell><Data ss:Type="String">value</Data></Cell>
hakre
  • 193,403
  • 52
  • 435
  • 836
user988201
  • 161
  • 1
  • 6
  • This helped solved my problem when building Excel files using simplexml in PHP. Thanks a lot. – Weboide May 31 '13 at 18:19
  • Note that this doesn't actually set the namespace for the attribute, though the result when serialized with [`SimpleXMLElement->asXML()`](http://php.net/SimpleXMLElement.asXML) is equivalent. Instead, "ss:" is part of the [local part](https://www.w3.org/TR/xml-names/#NT-LocalPart) of the attribute name. Compare the output of `$data->attributes('ss', TRUE)` and `$data->attributes()`. You can also use any prefix, not just "xmlns". – outis Sep 14 '16 at 07:10