Written by

Senior Cloud Architect at InterSystems
MOD
Question Eduard Lebedyuk · Nov 16, 2018

Update existing objects from XML

I have a XML enabled persistent class and a XML representation of some object of this class (object ID is available).
How can I use XML Reader (or some other mechanism) to automatically update this object?
 

Comments

Dmitry Maslennikov · Nov 16, 2018

The example in the documentation to %XML.Reader, does not work for you?

    #include %occStatus
    // Create a new XML Reader class
    Set reader = ##class(%XML.Reader).%New()
    // Begin processing of the XML input
    Set sc=reader.OpenFile(filename)
    If $$$ISERR(sc) Do $system.OBJ.DisplayError(sc) Quit  
    // Associate a class name with the XML element name
    Do reader.Correlate("Person","Sample.Person")
    // read Sample.Person objects from xml file
    Set Count=0
    While reader.Next(.person,.sc) {
        Write person.Name_" imported.",!
        Set Count=Count+1
        Set sc=person.%Save()
        If $$$ISERR(sc) Do $system.OBJ.DisplayError(sc) Quit  
    }
    If $$$ISERR(sc) Do $system.OBJ.DisplayError(sc) Quit  
    Write Count_" Sample.Person instances found."
0
Eduard Lebedyuk  Nov 16, 2018 to Dmitry Maslennikov

It would create a new object.

I want to update already existing object.

0
Eduard Lebedyuk  Nov 16, 2018 to Sean Connelly

Didn't knew you could do that with id.

0
Sean Connelly · Nov 16, 2018

Perhaps something along these lines...

ClassMethod UpsertXML(xml, wrapper, class, id, Output object) As %Status{  set reader=##class(%XML.Reader).%New()  $$$QuitOnError(reader.OpenString(xml))  do reader.Correlate(wrapper,class)  do reader.Next(.object,.sc)  $$$QuitOnError(sc)  if id'="" do object.%IdSet(id)  quit object.%Save()}

Usage...

w ##class(Foo.Person).UpsertXML("<Person><FirstName>Bob</FirstName><LastName>Smith</LastName><City>Paris</City></Person>","Person","Foo.Person",1)
0