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());
}

No comments:

Post a Comment