如何从Web服务的XML字符串中读取值

本文关键字:字符串 读取 XML Web 服务 | 更新日期: 2023-09-27 18:28:25

我在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回复结束///////////////////////////////我想把参数传递给数据库,比如:

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

如何从Web服务的XML字符串中读取值

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

您在这里可以做的是使用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;

正在尝试此代码。。

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

完全工作的