Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Check if and add element to XML file
Message
From
14/05/2018 06:01:11
Cetin Basoz
Engineerica Inc.
Izmir, Turkey
 
General information
Forum:
Visual FoxPro
Category:
Coding, syntax & commands
Miscellaneous
Thread ID:
01659959
Message ID:
01659972
Views:
64
>Hi,
>
>I am looking for an efficient way to check if an XML has an element, and if the element does not exist, add it.
>
>Here is an example:
>MyFile.xml:
>
><?xml version="1.0" standalone="yes" ?>
><Setting>
>   <MyElement1>123</MyElement1>
></Setting>
>
>
>Say, I want to find if this file (e.g. MyFile.xml) has element "MyElement2". And if not, add it.
>I can do it with FILETOSTRING(), STRTOFILE(), and STREXTRACT() functions. But I am not sure if this is the most efficient approach.
>
>Any suggestions? TIA

Yet another easy way is ti use XMLToCursor. If your XML is like that, then it is missing a root element to use with CursorToXML. Add it and then check if MyElement2 field exists or not. ie:
local myXML
myXML = '<root>'+StrExtract(FileToStr('MyFile.xml'), '<Setting>','</Setting>',1,4)+'</root>'
XMLToCursor(m.myXMl, 'tmp')

? Fsize('MyElement1','tmp') > 0
? Fsize('MyElement2','tmp') > 0
PS: This approach is also good for converting such a simple XML content to an object (after getting into cursor "scatter name oSetting memo"). Without a schema specified VFP decides on field types (ie: if a field has a value of 0 or 1 then it assumes that field is boolean).
Also if you do this with an existing cursor where your missing fields are defined (XMLToCursor(m.myXML, 'tmp', 8192), then that field would always exist with the default you want and you can get the XML with CursorToXML().
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform