简体   繁体   English

从xml文件检索数据

[英]Retrieve data from xml file

Below is a sample xml file with the data i'm after 以下是一个示例xml文件,其中包含我所需要的数据

<ns2:Response/">
<cacheKey>-7ca7484a:13e22cb1399:-47c0</cacheKey>
<cacheLocation>10.186.168.39:7302</cacheLocation>
</ns2:Response>

I have 2 classes, 1 class for getting xml data, this class then passes the data to another class that will have many other classes which extract the data. 我有2个类,其中1个类用于获取xml数据,然后该类将数据传递给另一个类,该类将具有许多其他类来提取数据。

public static string GetXmlData()
{
    string xmlPath = "url";
    var wc = new WebClient();
    wc.Headers.Add(HttpRequestHeader.ContentType, "application/xml");
    wc.Headers.Add(HttpRequestHeader.Accept, "application/xml");
    var xmlData = wc.DownloadString(new Uri(xmlPath));

    var xmlDoc = XDocument.Parse(xmlData);

    return xmlDoc.ToString();
}

The second clas has the following 第二个分类如下

public class GetCacheKey
{
    public string cacheKey { get; set; }
}

Below is where I'm having problem: 以下是我遇到的问题:

public IEnumerable<GetCacheKey> CacheKey()
{
    var doc = XDocument.Parse(GetXMLData());
    var xkey = from c in doc.Descendants("Response")
                select new GetCacheKey()
                    {
                        cacheKey = (string)doc.Element("cacheKey").Value  
                    };

    return xkey;
}

In debugger, it returns Empty = "Enumeration yielded no results" 在调试器中,它返回Empty =“枚举未产生任何结果”

So how can I get the value of cacheKey? 那么如何获取cacheKey的值?

There's actually two problems with your code. 您的代码实际上有两个问题。 First of all, doc.Descendants("Response") will not yield any results, because you've omitted the ns2 bit. 首先, doc.Descendants("Response")将不会产生任何结果,因为您省略了ns2位。 Secondly, doc.Element("cacheKey").Value should be c.Element("cacheKey").Value : 其次, doc.Element("cacheKey").Value应该是c.Element("cacheKey").Value

XNamespace ns2 = "http://namespaceurihere";

var xkey = from c in doc.Descendants(ns2 + "Response")
           select new GetCacheKey()
           {
               cacheKey = c.Element("cacheKey").Value
           };

Not really an issue, but the string cast in your code was redundant. 确实不是问题,但是代码中强制转换的字符串是多余的。

The namespace URI should be whatever URI you removed from the XML when you edited it for posting. 名称空间URI应该是您在编辑XML以进行发布时从XML中删除的任何URI。 It confuses people however, because <ns2:Response/"> is not valid XML. 但是,这使人们感到困惑,因为<ns2:Response/">不是有效的XML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM