Monday, October 29, 2012

Check if XML node exists in AX

Depending on where the XML is coming from, an XML node without a value may not come through as </Node> or <Node></Node> where 'Node' is the attribute/element of interest in this example. It may be completely left out depending on how things were coded.

In AX, if a node does not exist in the XML document and we try to read a value from a node that doesn't exist, a stack trace error is thrown. This is obviously not good.  We may need to 1) verify the node exists in the XML and then 2) extract the value.

For scenarios where this occurs, to prevent a stack trace error, you can do the below in the example where we may not have a 'RecId' node in the incoming XML.

XmlDocument   itemAndDateXml;
XmlElement    xmlRoot;   
XmlNodeList   xmlRecordList;
XmlElement    xmlItemRecord;
int           itemCounter;

itemAndDateXml = new XmlDocument();
itemAndDateXml.loadXml(_xml); // this is the xml string
xmlRoot = itemAndDateXml.documentElement().getNamedElement('Items');
xmlRecordList = xmlRoot.childNodes();

for (itemCounter = 0; itemCounter < xmlRecordList.length(); itemCounter++)
    xmlItemRecord = xmlRecordList.item(itemCounter-1);

    id      = xmlItemRecord.getNamedElement('Id').text();
    variant = xmlItemRecord.getNamedElement('Variant').text();
    qty     = str2Int(xmlItemRecord.getNamedElement('Qty').text());
    // Make sure that the node exists or the system will throw a stack trace error
    if (xmlItemRecord.selectSingleNode('RecId'))
        recId = str2recId(xmlItemRecord.getNamedElement('RecId').text());

Tuesday, October 2, 2012

Automatically format an XML string

Sometimes you get an XML string and it is unformatted. And doesn't have any tabbing and is hard to read. You can copy and paste this string into a box in the link below and it will do that formatting for you.

Fun tool that I use a lot of:

This is the XML string unformatted
<XML><Items><Item><Id>60000</Id><Varient>CEU-000001</Varient></Item> </Items></XML>'
This is the XML string after the formatting
<?xml version="1.0" encoding="UTF-8"?>

It is a really slick tool that is free to use. I know its saved me a ton of time.