views:

61

answers:

1

Using Delphi 2009, I'm trying to get a declared namespace prefix to apply to the document element in an IXMLDocument that I'm creating. Once the document element is created I can declare a namespace with a prefix, but it does not get applied to the document element and I can't seem to change the prefix of the document element. If I use doc.CreateElement(nodename, namespaceURI) to create the document element it add the specified URI as the default namespace for the doc, which is not what I want to do. This document that I'm creating is going to be added to another document that already had a default namespace.

  Result := NewXMLDocument;
  eleDoc := Result.CreateElement(TAG_IH_IMPORT, NS_HISTORIAN);
  eleDoc.DeclareNamespace(FNamespacePrefix, NS_HISTORIAN);

where TAG_IH_IMPORT and NS_HISTORIAN are string constants, eleDoc: IXMLNode and FNamespacePrefix: String.

The output of this looks like:

<Import xmlns="uri" xmlns:h="uri" />

I really want to get that "h:" applied to the Import tag. Any suggestions?

Thanks.

+2  A: 

You can specify the namespace prefix at the time you call CreateElement(), ie:

Result := NewXMLDocument;
eleDoc := Result.CreateElement(FNamespacePrefix + ':' + TAG_IH_IMPORT, NS_HISTORIAN);
eleDoc.DeclareNamespace(FNamespacePrefix, NS_HISTORIAN);
Result.DocumentElement := eleDoc;

Alternatively, you can create a temp document node, declare the prefix for its child nodes, add a child node to it, and then assign that as the new document node. For example:

Result := NewXMLDocument;
eleTemp := Result.CreateElement('temp', '');
eleTemp.DeclareNamespace(FNamespacePrefix, NS_HISTORIAN);
eleDoc := eleTemp.AddChild(TAG_IH_IMPORT, NS_HISTORIAN);
Result.DocumentElement := eleDoc;
Remy Lebeau - TeamB
Thanks, Remy. I had already implemented that second solution but hadn't yet got back here to post it. Your first suggestion is cleaner and I don't know why I didn't try it to begin with except that I just didn't expect that it would work.
RJCookeSE