How to set document item prefix in Delphi

Using Delphi 2009, I am trying to get the declared namespace prefix to apply to the document element in IXMLDocument that I create. After creating the document element, I can declare the namespace with a prefix, but it does not apply to the document element, and I cannot change the prefix of the document element. If I use doc.CreateElement (nodename, namespaceURI) to create a document element, it adds the specified URI as the default namespace for the document, which I don't want to do. This document that I am creating will 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 result of this looks like this:

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

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

Thanks.

+2
xml namespaces delphi
source share
1 answer

You can specify a namespace prefix during a call to CreateElement (), i.e.:

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

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

 Result := NewXMLDocument; eleTemp := Result.CreateElement('temp', ''); eleTemp.DeclareNamespace(FNamespacePrefix, NS_HISTORIAN); eleDoc := eleTemp.AddChild(TAG_IH_IMPORT, NS_HISTORIAN); Result.DocumentElement := eleDoc; 
+3
source share

All Articles