开发者

How to set the prefix of a document element in Delphi

开发者 https://www.devze.com 2023-01-05 05:20 出处:网络
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

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 FNam开发者_C百科espacePrefix: 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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消