Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse polymorphic XML

How would i parse an xml return from USPS's address validation if the markup changes depending on success?
For example, if the return is valid i get A) if not i get B). In A) the node <Error> does not exist and if there is an error i would like to output that error.
In PHP there is isset(), but ive never heard of anything like that for parsing XML.

A)

<?xml version="1.0"?>
<AddressValidateResponse>
    <Address ID="0">
        <Address2>123 MAIN ST</Address2>
        <City>SPRINGFIELD</City>
        <State>NY</State>
        <Zip5>11111</Zip5>
        <Zip4>1111</Zip4>
    </Address>
</AddressValidateResponse>

B)

<?xml version="1.0"?>
<AddressValidateResponse>
    <Address ID="0">
        <Error>
            <Number>-45DF6S45F</Number>
            <Source>API_AddressCleancAddressClean.CleanAddress2;SOLServer.CallAddressDll</Source>
            <Description>Address Not Found.  </Description>
            <HelpFile></HelpFile>
            <HelpContext>1000440</HelpContext>
        </Error>
    </Address>
</AddressValidateResponse>

Currently I am parsing xml using jquery like:

$.ajax({
    type: "POST",
    url: "usps_xml_verify.php",
    data: {<PASS IN VARIABLES>},
    dataType: "xml",
    success: function(xml) {
        $(xml).find('Address').each(function(){
            var Address2 = $(this).find('Address2').text();
            var Zip5 = $(this).find('Zip5').text();
            //etc...
        });
    }
}); 
like image 479
t q Avatar asked Mar 01 '26 03:03

t q


1 Answers

Instead of blindly iterating over the solution, first use find find method again to check if there is an error node:

var addr = $(xml).find('Address')

var err = addr.find('Error');
if(err.length > 0){
    //found at least one error node, process them here
}else{
    //no error nodes, continue normally:
    addr.each(function(){
        var Address2 = $(this).find('Address2').text();
        var Zip5 = $(this).find('Zip5').text();
        //etc...
    });
}

This is probably not the most idiomatic solution, but something like this should work. Don't forget that jQuery is just a Javascript library! You can call methods and put things in variables just like regular Javascript code.

like image 177
hugomg Avatar answered Mar 02 '26 16:03

hugomg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!