Search code examples
wpfxmlxmltextreaderxpathdocument

WPF - Searching an XML doc for values using XMLTextReader


Ok another WPF question, well I guess this is just general .NET. I have an xml document retreived from a URL.

I want to get multiple values out of the document (weather data, location, some other strings).

When I use the XmlTextReader I can call my method to pull the values out. The first time I pass the method to search for the xml node and get the value (the XMLTextReader object) I get the right data back, but then the XMLTextReader is dead. Not sure why it gets nulled out. So I'm having to do this UGLY code below in the FindTags... method. I want to just keep passing the xtr (XMLTextreader) back to my find method. Is this the nature of the reader? I don't want to have to hit the URL each time either... that seems wrong too.

Help.. this just all feels wrong.

Thanks.

        GetWeatherFeed("97229", "//weather//loc//dnam", "//weather//cc//tmp", "/weather/cc/icon");

Get WeatherFeed method (snipped)

        System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(Url that retuns xm);
        System.Collections.Hashtable ht = new System.Collections.Hashtable();

        ht = FindTagsUsingXPthNaviatorAndXPathDocumentNew(xtr, location, temperature, iconid);
        lblLocation.Content = ht["Location"].ToString();
        lblWeatherCondition.Content = ht["Weather"].ToString();


public System.Collections.Hashtable FindTagsUsingXPthNaviatorAndXPathDocumentNew(System.Xml.XmlTextReader xtr, string nodeToLocate1, string nodeToLocate2, string nodeToLocate3)
{
    System.Xml.XPath.XPathDocument xpDoc = new System.Xml.XPath.XPathDocument(xtr);
    System.Xml.XPath.XPathNavigator xpNav = xpDoc.CreateNavigator();
    System.Xml.XPath.XPathExpression xpExpression = xpNav.Compile(nodeToLocate1);

    System.Xml.XPath.XPathNodeIterator xpIter = xpNav.Select(xpExpression);
    System.Collections.Hashtable ht = new System.Collections.Hashtable();

    while (xpIter.MoveNext())
    {
        ht.Add("Location", xpIter.Current.Value);
    }

    xpExpression = xpNav.Compile(nodeToLocate2);

    xpIter = xpNav.Select(xpExpression);
    while (xpIter.MoveNext())
    {
        ht.Add("Weather", xpIter.Current.Value);
    }

    xpExpression = xpNav.Compile(nodeToLocate3);

    xpIter = xpNav.Select(xpExpression);
    while (xpIter.MoveNext())
    {
        ht.Add("Icon", xpIter.Current.Value);
    }

    return ht;
}

Solution

  • XmlTextReader cannot be reset to the beginning. Download you content first and then use multiple XmlTextReaders (if you have to).

    If the document you are downloading is small, I would just use an XmlDocument (or XDocument if you are using .NET 3.5)