开发者

.net 2.0 c# retrieving a value from xml

开发者 https://www.devze.com 2022-12-14 21:00 出处:网络
I realize this is a repost but I needed to as I can\'t use LINQ, ( requested in my previous post). I need to read the woeid from the XML doc below. I need to read and store the data into a string va

I realize this is a repost but I needed to as I can't use LINQ, ( requested in my previous post).

I need to read the woeid from the XML doc below. I need to read and store the data into a string variable so I can query the yahoo weather service.

XML returned by query:

<query yahoo:count="1"
       yahoo:created="2009-12-22T08:30:31Z"
       yahoo:lang="en-US"
       yahoo:updated="2009-12-22T08:30:31Z"
       yahoo:uri="http://query.yahooapis.com/v1/yql?q=select+woeid+from+geo.places+where+text%3D%22farnborough%2C+greater+london%2Cuk%22">

<diagnostics>
<publiclyCallable>true</publiclyCallable>

<url execution-time="32">
http://where.yahooapis.com/v1/places.q(farnborough%2C%20greater%20london%2Cuk);start=0;count=10
</url>
<user-time>33</user-time>
<service-time>32</service-time>
<build-version>4265</build-version>
</diagnostics>

<results>

<place>
<woeid>19941</woeid>
</place>
</results>
</query>

Can someone suggest how I could do this through XPath or another way which is compatible with the libraries in .net 2.0?

Thanks for the answers. As such I am using the method below, but I get an exception thrown when loading the XML document:

private string getWOEID(string UserLocation, string UserCountry)
{
    string woeID = "";

    if (UserLocation == "farnborough") { UserLocation = "farnborough" + "%2C" + "hampshire"; }

    String reqUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20woeid%20from%20geo.places%20where%20text%3D%22" + UserLocation + "%2C" + UserCountry + "%22&format=xml";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(reqUrl);
   string woeid = doc.SelectSingleNode("query/re开发者_C百科sults/place/woeid/text()").Value;
    return woeID;


}


The conventional way:

XmlDocument doc = new XmlDocument();
doc.Load(url);
string woeid = doc.SelectSingleNode("query/place/woeid/text()").Value;

A less conventional way of doing it:

int start = xmlString.IndexOf("<woeid>") + 7;
int end = xmlString.IndexOf("</woeid>", start);
string woeid = xmlString.Substring(start, end - start);

Anyone feel like running a benchmark?


I'll have another go at this, using ChaosPandion's post as a starting point:

    XmlDocument doc = new XmlDocument();
    using (XmlTextReader tr = new XmlTextReader(new StringReader(xmlString)))
    {
        tr.Namespaces = false;
        doc.Load(tr);
    }
    string woeId = doc.GetElementsByTagName("woeid")[0].InnerText;

Notice here that I'm deliberately ignoring namespaces here since you don't need them for what you are trying to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消