Wednesday, May 17, 2006

VFP: Inserting Nodes with XML Object

This was not a fun experiment. The key here is that we are using Visual Foxpro
to insert into a XML document. We do this by selecting the parent node, then insert
into the child nodes at a specific location. I dont see any other way to optimize this but I'm open for suggestions.





* OPEN MSXML Object
xmlDoc=CREATEOBJECT("Msxml2.DOMDocument.6.0")
xmlDoc.ASYNC="false"
xmlDoc.LOAD("xmltest.xml")
x=xmlDoc.documentElement

* INit document fragment
docFrag = xmlDoc.CreateDocumentFragment()

* Set the XML
docFrag.appendChild(xmlDoc.CreateElement("REF_J"))

* Obtain Original Node where children Exist
oNode=xmlDoc.selectnodes("/recordset/L.2000B/L.2300")
i=0
* Object Creation Of children nodes to iterate
objChildNodes = oNode.ITEM(0).childNodes
* Iterate through children, identify the node you want to insert before
FOR EACH strNode IN objChildNodes
** NODE IDENTIFIED, DO INSERT
IF strNode.nodename="REF_K"
* Inserting at the location of the node with children, insert before the location of the child node.
oNode.ITEM(0).insertBefore(docFrag, oNode.ITEM(0).childNodes.ITEM(i))
EXIT FOR
ENDIF
i=i+1
NEXT

* Save XML
xmlDoc.SAVE("xmltest-output.xml")


2 comments:

Rob said...

Good news, I found a faster way to make it work.

oNode=xmlDoc.selectnodes("/recordset/L.2000B/L.2300")
oBNode=xmlDoc.selectnodes("/recordset/L.2000B/L.2300/REF_K")
oNode.ITEM(0).insertBefore(docFrag, oBNode.Item(0))

And this works too

oBNode=xmlDoc.selectnodes("/recordset/L.2000B/L.2300/REF_K")
oBNode.Item(0).parentnode.insertBefore(docFrag, oBNode.Item(0))

Anonymous said...

Very nice tips!
Well done!