How can I evaluate an XPath expression in Silverlight?

I need to allow an advanced user to enter an XPath expression and show them found values ​​or found nodes or attributes. In the .Net framework, System.Xml.XPath.Extensions can be used to call XPathEvaluate, but Silverlight does not have this MSDN link . Has anyone rewritten extension methods for use in Silverlight? What is the best approach? Why aren't they available in Silverlight or in the toolbox ( vote for the question here )?

+5
source share
3 answers

One solution is to use a common processor and outsource processing on the server by asynchronous request. Here is a step by step:

First of all:

Create a shared handler in a web project . Add an ASHX file with the following code for your ProcessRequest (simplified for brevity):

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string xml = context.Request.Form["xml"].ToString();
        string xpath = context.Request.Form["xpath"].ToString();

        XmlReader reader = new XmlTextReader(new StringReader(xml));
        XDocument doc = XDocument.Load(reader);

        var rawResult = doc.XPathEvaluate(xpath);
        string result = String.Empty;
        foreach (var r in ((IEnumerable<object>)rawResult)) 
        {
            result += r.ToString();
        }

        context.Response.Write(result);

    }

It should be noted that there are some namespaces that you will need links to for processing XML:

  • System.io

  • System.xml

  • System.Xml.XPath

  • System.Xml.Linq

Second:

You need code that allows you to write asynchronously to a common handler. The code below is long, but essentially you pass the following:

  • Uri your common handler

  • Dictionary of key value pairs (assuming xml and xpath document)

  • Callbacks for success and failure

  • UserControl, ( ) .

, :

public class WebPostHelper
{
    public static void GetPostData(Uri targetURI, Dictionary<string, string> dataDictionary, Action<string> onSuccess, Action<string> onError, Dispatcher threadDispatcher)
    {
        var postData = String.Join("&",
                        dataDictionary.Keys.Select(k => k + "=" + dataDictionary[k]).ToArray());

        WebRequest requ = HttpWebRequest.Create(targetURI);
        requ.Method = "POST";
        requ.ContentType = "application/x-www-form-urlencoded";
        var res = requ.BeginGetRequestStream(new AsyncCallback(
            (ar) =>
            {
                Stream stream = requ.EndGetRequestStream(ar);
                StreamWriter writer = new StreamWriter(stream);
                writer.Write(postData);
                writer.Close();
                requ.BeginGetResponse(new AsyncCallback(
                        (ar2) =>
                        {
                            try
                            {
                                WebResponse respStream = requ.EndGetResponse(ar2);
                                Stream stream2 = respStream.GetResponseStream();
                                StreamReader reader2 = new StreamReader(stream2);
                                string responseString = reader2.ReadToEnd();
                                int spacerIndex = responseString.IndexOf('|') - 1;
                                string status = responseString.Substring(0, spacerIndex);
                                string result = responseString.Substring(spacerIndex + 3);
                                if (status == "success")
                                {
                                    if (onSuccess != null)
                                    {
                                        threadDispatcher.BeginInvoke(() =>
                                        {
                                            onSuccess(result);
                                        });
                                    }
                                }
                                else
                                {
                                    if (onError != null)
                                    {
                                        threadDispatcher.BeginInvoke(() =>
                                        {
                                            onError(result);
                                        });
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                string data2 = ex.ToString();
                            }
                        }
                    ), null);

            }), null);
    }
}

:

xml xpath:

    private void testButton_Click(object sender, RoutedEventArgs e)
    {
        Dictionary<string, string> values = new Dictionary<string, string>();
        values.Add("xml", "<Foo />");
        values.Add("xpath", "/*");

        //Uri uri = new Uri("http://eggs/spam.ashx");
        Uri uri = new Uri("http://localhost:3230/xPathHandler.ashx");

        WebPostHelper.GetPostData(uri, values,
            (result) =>
            {
                MessageBox.Show("Your result " + result);
            },
            (errMessage) =>
            {
                MessageBox.Show("An error " + errMessage);
            },
            this.Dispatcher);

    }

, . , . " " , context.Request.Form. .

0

, , XPath Silverlight, , MS , Linq XML. . , , , . , , , . , , .

+1

Now comes the NuGet package that provides this feature. The author is listed as Microsoft.

0
source

All Articles