Published on InterSystems Developer Community (https://community.intersystems.com)

Home > How to Manipulate XML to Formatted String

Question
Thembelani Mlalazi · Nov 14, 2017

How to Manipulate XML to Formatted String

I am using studio 2015 version which does not have dynamic objects and I need to read xml and convert that to a json I have managed to come close to json string but with little difficulties .I need to be able to identify the root element and specify where to put braces between objects  anyone  with any idea is welcome he is my code so far

ClassMethod WriteNodes(myfile As %String = "C:\Testdata\data.xml")
{
  set status=##class(%XML.TextReader).ParseFile(myfile,.textreader)
  
    if $$$ISERR(status)
      {
	    do $System.Status.DisplayError(status) 
	    quit
	  }

       set ptemp=##class(%Stream.FileCharacter).%New()
       set ptemp.Filename="C:\Testdata\ree.txt"
      //check status
     //iterate through document, node by node
  
       Do ptemp.Write( "{")
       while textreader.Read()
        {
           If (textreader.seq=462)
	         {
		       Do ptemp.Write("}")
		       Do ptemp.Write("]")
		       Do ptemp.Write("}")
		     }
		     
		       If ((textreader.Path="/[1]/[2]/[0]")&&(textreader.NodeType'= "endelement"))
	             {
		          Do ptemp.Write("{")
		         }
		            If ((textreader.Path="/[1]/[2]/[0]")&&(textreader.NodeType= "endelement"))
	                   {
		                Do ptemp.Write("},")
		              }
        
                   If ((textreader.Name'="")&&(textreader.NodeType'= "endelement"))
                      {
                        Do ptemp.Write($CHAR(34)_textreader.Name_$CHAR(34)_$CHAR(58))
                      }
                      Else
                      {
	                   Do ptemp.Write("")
	                  }
           
                  If (textreader.Value'="")
                     {
                      Do ptemp.Write($CHAR(34)_textreader.Value_$CHAR(34)_"," )
                     }
               Do ptemp.WriteLine()
        }

       Do ptemp.%Save()
       
       quit
}
#JSON #XML #Caché

Source URL:https://community.intersystems.com/post/how-manipulate-xml-formatted-string