3

my source like this in C#:

string xml = null;
WebRequest req = WebRequest.Create("https://www.freegeoip.net/xml");
req.Credentials = CredentialCache.DefaultCredentials;
WebResponse res = req.GetResponse();
Stream dataStream = res.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
xml = reader.ReadToEnd();
reader.Close();

res.Close();

am getting response like this :

<?xml version="1.0" encoding="UTF-8"?>
    <Response>
        <IP>162.158.50.10</IP> //IP address
        <CountryCode>IN</CountryCode>   //Country Code
        <CountryName>India</CountryName>//Country Name
        <RegionCode>MH</RegionCode> //Region Code
        <RegionName>Maharashtra</RegionName>
        <City>Mumbai</City>
        <ZipCode></ZipCode>
        <TimeZone>Asia/Kolkata</TimeZone>
        <Latitude>18.975</Latitude>
        <Longitude>72.8258</Longitude>
        <MetroCode>0</MetroCode>
    </Response>

/// XMl Reponse END/////////////////////////////// I want pass parameters to Database like :

 objLogDetails.IPAddress  = ???? //Here i want to pass IP :162.158.50.10 from XMl string 

3 Answers 3

4

HEre are two methods, one using xpath and the other using linq 2 xml:

using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace stackexchange
{
    class Program
    {
        private static string theXml = @"<?xml version='1.0' encoding='UTF-8'?>
    <Response>
        <IP>162.158.50.10</IP> //IP address
        <CountryCode>IN</CountryCode>   //Country Code
        <CountryName>India</CountryName>//Country Name
        <RegionCode>MH</RegionCode> //Region Code
        <RegionName>Maharashtra</RegionName>
        <City>Mumbai</City>
        <ZipCode></ZipCode>
        <TimeZone>Asia/Kolkata</TimeZone>
        <Latitude>18.975</Latitude>
        <Longitude>72.8258</Longitude>
        <MetroCode>0</MetroCode>
    </Response>";
        static void Main(string[] args)
        {
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(theXml);
            XmlNode ip = xml.SelectSingleNode("/Response/IP");
            Console.Out.WriteLine($"Ip Address: {ip.InnerText}");

            XElement root = XElement.Parse(theXml);
            XElement address = (from a in root.Descendants() where a.Name == "IP" select a).Single();
            Console.Out.WriteLine($"Ip Address: {address.Value}");
        }
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

If you are using XElement, why not just XPathSelectElement? why go through all the trouble? this dosen't make sense.
because I had a brain fart, I just woke up and barely sipped my coffee yet, lol
Error 'string' does not contain a definition for 'SelectSingleNode' and no extension method 'SelectSingleNode' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
i got above error for asp.net ( XmlNode ip = xml.SelectSingleNode("/Response/IP");)
did you grab the using statements at the top? missing a library in references?
|
1

What you can do here, is use an XElement to get items from the response and insert into your request.

You can do so like this:

//sets the node or remove
     public static void SetOrRemoveNodeValue(XElement root, string xPath, string attributeName, string value)
            {
                XElement currentNode = root.XPathSelectElement(xPath);
                if (currentNode != null)
                {
                    if (currentNode.Attributes().FirstOrDefault(att => att.Name.LocalName.Equals(attributeName)) != null)
                    {
                        if (value == string.Empty)
                        {
                            currentNode.Attribute(attributeName).Remove();
                        }
                        else
                        {
                            currentNode.Attribute(attributeName).Value = value;
                        }
                    }

then use it like this:

 Formatter.SetOrRemoveNodeValue("node", "your value type", "your value");

To extract value from the response, simply use:

currentNode.XPathSelectElement("//Response").Element("Ip").value;

Or simply
currentNode.XPathSelectElement("//Ip").value;

Comments

-2

Trying This Code ..

private string mStrXMLStk = Application.StartupPath + "\\Path.xml";
private System.Xml.XmlDocument mXDoc = new XmlDocument();
mXDoc.Load(mStrXMLStk);
XmlNode XNode = mXDoc.SelectSingleNode("/Response");
if (XNode != null)
{
   if (XNode != null)
   {
       int IntChildCount = XNode.ChildNodes.Count;
       for (int IntI = 1; IntI <= 1; IntI++)
       {
            string LocalName = XNode.ChildNodes[IntI].LocalName;
            XmlNode Node = mXDoc.SelectSingleNode("/Response/" + LocalName);
            string _ip = Node.InnerText;
            MessageBox.Show("IP" + _ip);
       }
   }
}

Completely worked

3 Comments

my scenario not like this .
On line 4 you could have selected the node you wanted instead of looping: mXdoc.SelectSingleNode("/Response/Ip");
if they want countrycode or countryname or anything from nodes thats why i used loop otherwise for one node "IP" Following this mXdoc.SelectSingleNode("/Response/Ip")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.