views:

224

answers:

2

It's a novice question so be kind to me :)

How can I consume a php API in ASP.NET? This API returns an XML document. It is also capable of returning JSON.

The output is shown below

XML

<?xml version="1.0" encoding="UTF-8"?>

<Address>

        <Country>US</Country>

        <City>Seattle</City>

        <Result>Done</Result>

</Address>

JSON

{

"CountryCode" : "US",

"City" : "Seattle",

"Result" : "Done"

}

For eg: there is a service http://someservice.com/name_query.php?pincode= which accepts pincode and returns an XML document.

Can I use LINQtoXML and consume it. Please an example of consuming with XML and one with JSON will be very helpful.

+3  A: 

You can use LINQtoXML, you can use the XMLDom. What language are you going to be using C# or VB.NET?

one way to do this in LINQ to XML:

var XML = XElement.Parse(xmlSourceString);
        var query = from a in XML.Descendants("addressXML")
                    select new
                               {
                                   Country = a.Element("Country").Value,
                                   City = a.Element("City").Value
                               };
David Yancey
thanks david..how can i get the xmlSourceString from url that returns XML or JSON?
Musa
You would set the variable xmlSourceString to the XML returned from the opening the URL and reading the stream by using a WebClient as balexandre describes.
David Yancey
thanks so much for your answer
Musa
like: var XML = XElement.Parse( GetDocument(myPinCode) );
balexandre
Your welcome. One very powerful aspect of XLINQ (LINQtoXML) and any other flavor of LINQ for that matter is the ability to project your query into an anonymous type (as I did in my example) or into an actual type. I would suggest working with what ever XML dom you are familiar with first and then learn LINQtoXML.
David Yancey
There are two ways you can load an XML into LINQtoXML. If you know you are going to have a string then you would use XElement.Parse which takes a string as the param. If you have a stream then you would use XDocument.Load instead of XElement.Parse.
David Yancey
Thanks again..Will I be consuming the JSON also using the WebClient class?
Musa
+4  A: 

Hi Musa,

XML vs JSON first

if you are going to use the API to perform some AJAX queries (like, query the API as the user click a link/image and you, for example, want to change the color of that link, witch will tell the user that it's ok or not... go for JSON because you no need to parse the XML)

if you are doing everything behind the "bushes" and you only need to present data that is processed in the code behind, then use XML.

Simple use, with WebClient object

private string GetDocument(string myPin) {
   String url = String.Format("http://someservice.com/name_query.php?pincode={0}", myPin);

   WebClient client = new WebClient();
   client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;)"); // pass as Internet Explorer 7.0

   Stream data = client.OpenRead(url);
   StreamReader reader = new StreamReader(data);
   s = reader.ReadToEnd();
   data.Close();
   reader.Close();

   return s;
}

at this time, you have the entire XML that you got from the API in a string, all you need now is to process the XML, for example, like:

imagine that the output is an XML document like:

<Hit dbId="400179221" systemId="115">
    <WorksiteDbId>200105072</WorksiteDbId>
    <Subscribed>false</Subscribed>
    <FirstName>Klaus Holse</FirstName>
    <LastName>Andersen</LastName>    
    <Status>Active</Status>
    <MainJobTitle>CEO (Managing Director, General Manager, Owner)</MainJobTitle>
    <WorksiteName>Microsoft Development Center Copenhagen ApS </WorksiteName>
    <Department></Department>
    <Address></Address>
    <Zipcode></Zipcode>
    <City></City>
    <WorksitePhone></WorksitePhone>
    <TypeCode>TY10</TypeCode>
    <WorksiteStatus>Active</WorksiteStatus>
</Hit>

the method to process the document information is something like:

private void processDocument(string myPin) {

    String xml = GetDocument(myPin);
    XmlTextReader reader = new XmlTextReader(new StringReader(xml));
    XmlDocument document = new XmlDocument();
    document.Load(reader);

    XmlNodeList list = document.SelectNodes("/XMLNode/XMLSubNode");

    foreach (XmlNode node in list)   // loop through all nodes
    {
        foreach (XmlAttribute att in node.Attributes)  // loop through all attributes
        {
            switch (att.Name.ToLower())
            {
                case "dbid": myClass.DbID = Int32.Parse(att.InnerText); break;
                case "systemid": myClass.SystemID = Int32.Parse(att.InnerText); break;
                default: break;
            }
        }

        foreach (XmlNode subnode in node.ChildNodes)  // loop through all subnodes
        {
            switch (subnode.Name.ToLower())  // check what node has what
            {
                case "subscribed": myClass.Subscribed = bool.Parse(subnode.InnerText); break;
                case "firstname": myClass.Firstname = subnode.InnerText; break;
                case "lastname": myClass.Lastname = subnode.InnerText; break;
                case "status": myClass.Status = subnode.InnerText; break;
                ...
            }
        }
    }
}

you will have myClass filled up with all values that were returned by the API...

as you mention in the first line... this is for novice :) and it's a good way to you understand the concept of getting and use XML data... after you understand this part, then you will move easily to LINQ2XML :)

I hope this helps...


added

because I only saw now that you have the output of the XML, here is the processDocument method to use the exact XML

xml:

<?xml version="1.0" encoding="UTF-8"?>
<Address>
        <Country>US</Country>
        <City>Seattle</City>
        <Result>Done</Result>
</Address>

method:

private void processDocument(string myPin) {

    String xml = GetDocument(myPin);
    XmlTextReader reader = new XmlTextReader(new StringReader(xml));
    XmlDocument document = new XmlDocument();
    document.Load(reader);

    XmlNodeList list = document.SelectNodes("/Address");

    foreach (XmlNode node in list)   // loop through all nodes
    {
        foreach (XmlNode subnode in node.ChildNodes)  // loop through all subnodes
        {
            switch (subnode.Name.ToLower())  // check what node has what
            {
                case "country": myClass.Country =subnode.InnerText; break;
                case "city": myClass.City= subnode.InnerText; break;
                case "result": myClass.Result = subnode.InnerText; break;
            }
        }
    }
}

remember to check for errors, like passing a wrong set of data so you can handle the error correctly.

:-)

balexandre
thanks for explaining so well..In a real app, what would you use if you were to do it(advanced approach)
Musa
in a product to sell from the company I work for, I'm using the XML approach just I described :) the future versions will probably use Linq2Xml but never JSON cause the WebService that I use does not output JSON, if I had that chance, I would use it for example when I'm showing a result grid for the PAGING part... works great and fast like this, with LIN2XML it would be a little faster, but save in several lines of code. go for the simplest one first.
balexandre
thanks a ton balexandre!!
Musa
Just one last thing..Will I be consuming the JSON also using the WebClient class?
Musa
depend where are you calling, but normally, no, that you will use jQuery.Ajax() method :) it's simple and much faster ;)
balexandre
do u need the code?
balexandre