Having hard time with IDOMNode and IXMLNode distinction. I want to append a child element in a document to a node selected with XPath.
What I tried:
Effort 1:
I get an XPath result node N:IDOMNode from IDOMNodeSelect.selectNodes(expression);
If I convert it back to IXMLNode using
intfDocAccess : IXmlDocumentAccess;
doc: TXMLDocument;
...
if Supports( N.OwnerDocument, IXmlDocumentAccess, intfDocAccess) then
doc := intfDocAccess.DocumentObject
else
doc := nil;
NodeAsIXMLNode := TXmlNode.Create( N, nil, doc );
...then adding a child to it throws access violation. Probably NodeAsIXMLNode is not even in the original document, it's just a copy created for type compatibility...
Effort 2:
Try to add a child node to the XPath result node directly:
XMLNode := XmlDoc.CreateElement( 'tag', '' );
N.appendChild( XMLNode as IDOMNode );
It throws Interface not supported. I have a feeling that the xpath result IDOMNode node is also not a member of the original IXMLDocument, just some result copy. Just a guess.
So how could I select a node using xpath, then append a child element node to it? So my original IXMLDocument gets updated.
Update: Traversing the whole xml document tree and comparing the IXMLNode's DOMNode with the XPath result DOMNode also not working - XPath result nodes are not contained in the original doc, it turns out. Tried msxml, adom and omnixml implementations /XE7/
Update 2: Managed to work with the first method, just replacing
doc := nil;
with
doc := _xpathdoc as TXMLDocument; // _xpathdoc : the IXMLDocument
in the converter function.
IDOMNode
back into the originalIXMLNode
, andselectNodes()
does not report where DOM nodes were found within the document. Iterating the document looking for matching nodes defeats the purpose of using XPath, you may as well just iterate the document manually in the first place and not use XPath at all. – Remy Lebeaudoc := TXMLDocument(_xpathdoc);
is considered an "unsafe" typecast and will returnnil
if the cast fails. A "safe" cast is to use theas
operator instead so it raises an exception if the cast fails:doc := _xpathdoc as TXMLDocument;
. See Casting Interface References to Objects on Embarcadero's DocWiki. – Remy Lebeau