Wednesday, February 27, 2013

Parse out a node from an XML in AX 2012

Parsing out nodes from an XML is fairly easy in AX if you know what you're doing. I'm going to show how I do a basic XML parse.

For this example, the AX system can receive an XML that can either be for a quotation or sales order. There are multiple items in this request. We will need to cycle through the lines, do a process of some type (I will not share this as it wouldn't help anyone out), and finally, send that same XML back to the previous system indicating that a node changed. This node changed can be processed, an adjusted quantity, or whatever you really want.

I have a sample XML as well as the code which will:
  1. grab a node in the XML root and get the value
  2. cycle through the items sent in the XML
  3. grab a quantity from the attributes in the item nodes
  4. change a value in the item nodes
Hope this helps.



public static server XML daxXMLTest(str _custOrderXmlStr)
{ 
   XmlDocument custOrderXml;
   XmlElement  xmlRoot;
   XmlElement  xmlRecord;
   str         orderType;
   XmlNode     xmlNode;
   XmlNodeList xmlRecordList;
   RecId       lineRecId;
   int         i;

   custOrderXml = new XmlDocument();
   custOrderXml.loadXml(_custOrderXmlStr);
   xmlRoot = custOrderXml.documentElement().getNamedElement('Items');
   xmlRecordList = xmlRoot.childNodes();

   // Grab a value 
   xmlNode = custOrderXml.documentElement().selectSingleNode('OrderType');
   orderType = xmlNode.text();

   if(xmlRecordList)
   {
      // Cycle through the items in the incoming XML
      for (i = 0; i < xmlRecordList.length(); i++)
      {
         // Grab the item in the XML that corresponds to the iteration number
         xmlRecord = xmlRecordList.item(i);

         // Parse out local variables
         lineRecId = str2int64(xmlRecord.getAttribute('RecId'));
         ...

         // Do the magic
         ...

         // Change value in the XML that was sent to AX so we can return it with new values
         // I'm setting the example 'newValue' to true just out of simplicity
         newValue = true;
         xmlRecord.setAttribute('NodeToChange', newValue);
      }
   }
}

return custOrderXml.toString();

2 comments:

  1. I think the things you covered through the post are quiet impressive, good job and great efforts. I found it very interesting and enjoyed reading all of it.
    Microsoft Dynamics AX Training | Microsoft Dynamics CRM Online Training

    ReplyDelete
  2. I have an issue with generating XML from AX (4.0). Specifically, needing to add attributes to the root node. I'd be happy to share the code if someone could give me some pointers.

    ReplyDelete