如何从Web Service中读取XML String中的值

时间:2015-12-29 10:24:45

标签: c# xml

我在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();
我得到这样的回应:

<?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 ///////////////////////////////   我想将参数传递给数据库,如:

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

3 个答案:

答案 0 :(得分:3)

是两种方法,一种使用xpath,另一种使用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}");
        }
    }
}

答案 1 :(得分:1)

您可以在此处执行的操作是使用XElement从响应中获取项目并插入到您的请求中。

你可以这样做:

//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;
                        }
                    }

然后像这样使用它:

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

要从响应中提取值,只需使用:

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

或者干脆 currentNode.XPathSelectElement("//Ip").value;

答案 2 :(得分:-2)

尝试此代码..

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

完全工作