locked
C# event handler for load XML RRS feed

  • Question

  • What is the code used to link a XML using a event handler?

    Example

    Comboboxitem Item
    Comboboxitem Test


     private void Test_Selected(object sender, RoutedEventArgs e)
            {
               (code to load a certain .XML file)
              

            }  
     private void Item_Selected(object sender, RoutedEventArgs e)
            {(code to load a certain .XML file)
              

            }  
    Wednesday, January 12, 2011 5:17 AM

All replies

  • string strUri = "FilePath.xml";
          WebClient client = new WebClient();
          client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
          client.DownloadStringAsync(new Uri(strUri, UriKind.Relative));
        }
    
        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
          pnlCust.Children.Clear();
          Image image = null;
          XmlReader reader = XmlReader.Create(new StringReader(e.Result));
          while (reader.Read())
          {
            if (reader.NodeType == XmlNodeType.Element)
            {
             }
          }
          reader.Close();
        }
    
    Hope this helps
    • Proposed as answer by Stef S Wednesday, January 12, 2011 7:37 AM
    Wednesday, January 12, 2011 7:37 AM
  • hello,

    just to make sure.

    do i put this under the event handler?


    and I am getting red line errors under:


    string strUri = "Japanese.xml";
    WebClient client = new WebClient ();

     client.DownloadStringCompleted += new DownloadStringCompletedEventHandler (client_DownloadStringCompleted);
    client.DownloadStringAsync(new Uri(strUri, UriKind.Relative));


    void client_DownloadStringCompleted (object sender, DownloadStringCompletedEventArgs e)
        {
          pnlCust .Children.Clear();
          Image image = null;
          XmlReader reader = XmlReader .Create(new StringReader (e.Result));
          while (reader.Read())
          {
            if (reader.NodeType == XmlNodeType .Element)
            {
             }
          }
          reader.Close();
        }

     

    :/

    Thursday, January 13, 2011 12:56 AM
  • You have to put the first code block

    into your event handlers

    private void Item_Selected(object sender, RoutedEventArgs e)
        {(code to load a certain .XML file)
          
    <pre lang="x-c#">	string strUri = "FilePath.xml";
      	  WebClient client = new WebClient();
     	  client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
      	  client.DownloadStringAsync(new Uri(strUri, UriKind.Relative));
    
    
    }

    What kind of error (red linles) do you get?

    Thursday, January 13, 2011 5:54 AM
  • i am getting namespace name '' could not be found for all redl ine
    Thursday, January 13, 2011 6:13 AM
  • For the WebClient you have to use System.Net.
    The Xml stuff needs System.Xml.
    Maybe you alse need System.IO

    The pnlCust is a code snipped from me :D. Sorry. You can delete it.

    Thursday, January 13, 2011 6:27 AM
  • The above works for the error.

    Do you mind if i ask something extra here

     

    For the event handling part done,
    How do i make it so that when the xml is loaded through this combo box select

    The content from the XML will be transfer to the window.

    My purpose for loading the xml is to change the content of the buttons and the textboxes etc, i don't know if my XMl is correct or wrong.

     

    here is some parts of XML copied from my XML(it's suppose to change the "language" of the buttons to japanese, the other XML is English contents.


    Japanese.xml:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xmlDataSetSimplified xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <DataSet>
            <id>1</id>
            <Content>Welcome!</Content>
            <Japanese>ようこそ!</Japanese>
        </DataSet>
        <DataSet>
            <id>2</id>
            <Content>installBtn</Content>
            <Japanese>インストール</Japanese>
        </DataSet>
        <DataSet>
            <id>3</id>
            <Content>backBtn</Content>
            <Japanese>Back</Japanese>
        </DataSet>

     

     

    For English.xml

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xmlDataSetSimplified xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <DataSet>
            <id>1</id>
            <Content>Welcome!</Content>
            <English>Welcome!</English>
        </DataSet>
        <DataSet>
            <id>2</id>
            <Content>installBtn</Content>
            <English>Guided Install</English>
        </DataSet>
        <DataSet>
            <id>3</id>
            <Content>backBtn</Content>
            <English>Back</English>
        </DataSet>

     

    Thursday, January 13, 2011 8:12 AM
  • Why don't you use the same structure of the XML-files? With your two versions you have to create different parsers for getting the content out of the elements
    I suggest you to use the same structure for both of the files and write one wrapper. So you have to create a method which looks for the control and read out the content.

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xmlDataSetSimplified xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <DataSet>
        <id>1</id>
        <Control>Welcome!</Control>
        <Content>Welcome!</Content>
      </DataSet>
      <DataSet>
        <id>2</id>
        <Control>installBtn</Control>
        <Content>Guided Install</Content>
      </DataSet>
      <DataSet>
        <id>3</id>
        <Control>backBtn</Control>
        <Content>Back</Content>
      </DataSet>
    
    
    
    
    Thursday, January 13, 2011 8:37 AM
  • i am so sorry, could you explain a little more in details, because i am abit lost  x.x
    Thursday, January 13, 2011 8:45 AM
  • on the XML
    do you mean making both the xml have

    <id><control><content>

    instead of

    <id><content><japanese>
    <id><content><english>

     

     

    and could you explain on how to create the method which looks for the control and read content? Sorry for the big trouble :<

    Thursday, January 13, 2011 9:48 AM
  • you can try something like this after getting the XMLReader filled up

     while (reader.Read())
          {
            if (reader.NodeType == XmlNodeType.Element)
            {
              object o = this.LayoutRoot.FindName(reader["Control"]);
              if (o!=null)
              {
                switch (reader["Type"])
                {
                  case "TextBlock":
                    ((TextBlock)o).Text = reader["Content"];
                    break;
                  case "Button":
                    ((Button)o).Content = reader["Content"];
                    break;
                }
              }
              
            }
          }
          reader.Close();
    

    and your xml my be look like this

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xmlDataSetSimplified xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Control id="1" Type="Label" Name="lblTitle" Content="Welcome!" />
    <Control id="2" Type="Button" Name="btnInstall" Content="Install me!" />
    
    
    Thursday, January 13, 2011 12:33 PM
  • i've got a error at

    reader.Close();

    Invalid token'(' in class, struct, or interface member declaration

     

    Friday, January 14, 2011 1:12 AM
  • i think i solved the reader.Close(); problem

     

    i ran my application and when i changed my combo box to japan

    i got an yellow higher error at

     XmlReader reader = XmlReader.Create(new StringReader(e.Result));

    TargetInvocationException was unhandled

    An exception occurred during the operation, making the result invalid.  Check InnerException for exception details.

    Friday, January 14, 2011 1:15 AM
  • also trialed and error again and got this

    the type or namespace name 'DownloadStringEventsArgs' could not be found (are you missing a using directive ...)
    Friday, January 14, 2011 1:33 AM
  • You have to use
    using System.Net für DownloadStringCompletedEventArgs

    Again the code for loading the xml content

    <span style="color:#0000ff; font-size:x-small"><span style="color:#0000ff; font-size:x-small"><font size="2" color="#0000ff"><font size="2" color="#0000ff"><p>using</p></font></font></span><font size="2" color="#0000ff"><p> </p></font></span><p><span style="font-size:x-small"> System.Xml;</span></p><span style="color:#0000ff; font-size:x-small"><span style="color:#0000ff; font-size:x-small"><font size="2" color="#0000ff"><font size="2" color="#0000ff"><p>using</p></font></font></span><font size="2" color="#0000ff"><p> </p></font></span><p><span style="font-size:x-small"> System.IO;</span></p><span style="color:#0000ff; font-size:x-small"><span style="color:#0000ff; font-size:x-small"><font size="2" color="#0000ff"><font size="2" color="#0000ff"><p>using</p></font></font></span><font size="2" color="#0000ff"><p> </p></font></span><p><span style="font-size:x-small"> System.Net;</span></p>
    
    private void Item_Selected(object sender, RoutedEventArgs e)
    {
      WebClient client = new WebClient();
      client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
      client.DownloadStringAsync(new Uri("YourFile.xml", UriKind.Relative));
    }
    
    void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
     XmlReader reader = XmlReader.Create(new StringReader(e.Result));
    ...
    }
    
    Friday, January 14, 2011 6:18 AM
  • i inputted

    using System.Net;

    and also replace the yourfile.xml with my xml name and i still got the same error ;/
    Friday, January 14, 2011 6:22 AM
  • i have an error unrelated to this too

     

    system.windows.input.mouseeventargs hides inherited member 'system.windows.uielement.mouseleave'. use the new keyword if hiding was intended

    Friday, January 14, 2011 6:26 AM
  • Do you have made an interface or custom function with your mouseevent?
    Friday, January 14, 2011 10:25 AM
  • i don't think so

     

    here is the content of my event handler for the mousevent

     private void MouseLeave(object sender, MouseEventArgs e)
            {
                descriptionRect.Visibility = Visibility.Hidden;
                descriptionText.Text = "";
                imageChange.Source = null;
                usbHover.Visibility = Visibility.Hidden;
                ethernetHover.Visibility = Visibility.Hidden;
                wirelessHover.Visibility = Visibility.Hidden;
            }

     

    is it the imageChange.Source=null affecting it?

    Monday, January 17, 2011 12:49 AM
  • i think i manage to solve this problem by changing the event handler name
    However , i see more errors like

    Possible unintended reference comparison; to get a value comparison, cast
    the left hand side to type String

     

    The name 'XmlReader' does not exist in the current context

    The type or namespace namer 'StringReader' could not be found ( are you missing a using directive or an assembly reference?)

    the variable 'strUri' is assigned but its value is never used







    This application was passed down by a previous person to me , so there are quite some code that are not done by me

    i will try the whole thing again with the default application given, also could you tell me, do i need to bind the XML or anything onto the application?









    An extra question, do i need to add in any code in the XAML area  like, the control ID or something

    Monday, January 17, 2011 12:56 AM
  •  

    i tried do

    ing all this inside a new empty file and i got a debug error

    private
     void
     Item_Selected(object
     sender, RoutedEventArgs e)
    {
    WebClient client = new WebClient();
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    client.DownloadStringAsync(new Uri("Japan.xml" , UriKind.Relative));
    }

    void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
    XmlReader reader = XmlReader.Create(new StringReader(e.Result));
    ...
    }




    i tried the codes, and i still got the same error at

    XmlReader reader = XmlReader.Create(new StringReader(e.Result));     

    The line was highlighted in yellow
    Error: TargetInvocationException was unhandled

    Monday, January 17, 2011 4:38 AM
  • Error of Blank file is

    WpfApplication3 -> C:\Documents and Settings\081950G\My Documents\Expression\Blend 4\Projects\WpfApplication3\WpfApplication3\bin\Debug\WpfApplication3.exe
    The build has successfully completed.
    Unhandled Exception: System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid.  Check InnerException for exception details. ---> System.Net.WebException: An exception occurred during a WebClient request. ---> System.InvalidOperationException: This operation is not supported for a relative URI.
       at System.Uri.get_Query()
       at System.Net.WebClient.GetUri(Uri address)
       at System.Net.WebClient.DownloadStringAsync(Uri address, Object userToken)
       --- End of inner exception stack trace ---
       --- End of inner exception stack trace ---
       at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
       at System.Net.DownloadStringCompletedEventArgs.get_Result()
       at WpfApplication3.MainWindow.client_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e) in c:\Documents and Settings\081950G\My Documents\Expression\Blend 4\Projects\WpfApplication3\WpfApplication3\MainWindow.xaml.cs:line 43
       at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
       at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
       at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at WpfApplication3.App.Main() in c:\Documents and Settings\081950G\My Documents\Expression\Blend 4\Projects\WpfApplication3\WpfApplication3\obj\Debug\App.g.cs:line 0


    Monday, January 17, 2011 4:46 AM
  • Do you make a Silverlight or a WPF application?
    Monday, January 17, 2011 5:51 AM
  •  erm i am making a WPF App
    Monday, January 17, 2011 5:58 AM
  • that changes everything :D

    My codesnippeds are for an SL application.
    I'll try to give you a WPF solution.

    Monday, January 17, 2011 6:07 AM
  • ok , i want to thank you first for the help stef :D

     

    thank you :D

    Monday, January 17, 2011 6:19 AM
  • For loading an XML File in WPF:

     private void LoadXML()
        {
          string strFile = @"FilePath\Filename.xml";
    
          try
          {
            XmlDocument doc = new XmlDocument();
            doc.Load(strFile);
    
            XmlElement root = doc.DocumentElement;
            
    
            foreach (XmlNode node in root.ChildNodes)
            {
              Console.WriteLine(node.Attributes["Type"].Value);
              Console.WriteLine(node.Attributes["Name"].Value);
              Console.WriteLine(node.Attributes["Content"].Value);          
            }
          }
          catch (Exception ex)
          {
            MessageBox.Show(ex.Message);
          }
    
    • Proposed as answer by Stef S Tuesday, January 18, 2011 6:35 AM
    Tuesday, January 18, 2011 6:31 AM
  • how do i call the content in the xml out to the buttons and textblock?

     for example


    Button  (to show "install")   taking content from xml file -> installBtn
    TextBlock(to show Welcome!)  taking content from xml ->  welcome!

     

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xmlDataSetSimplified xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Control id="1" Type="Label" Name="lblTitle" Content="Welcome!" />
    <Control id="2" Type="Button" Name="btnInstall" Content="Install" />

    Tuesday, January 18, 2011 11:40 AM
  • 
    
    try the following code
     XmlDocument doc;
     public MainWindow()
     {
      InitializeComponent();
      LoadXML();
      GetTextForControl();
      
     }
    
     private void GetTextForControl()
     {
      foreach (UIElement element in spTest.Children)
      {
      if (element is Button)
      {
       ((Button)element).Content = FindTextForControl(((Button)element).Name);
      }
      if (element is TextBlock)
      {
       ((TextBlock)element).Text = FindTextForControl(((TextBlock)element).Name);
      }
      }
     }
    
     private string FindTextForControl(string sName)
     {
      string strText = string.Empty;
    
      XmlNode node = doc.DocumentElement.SelectSingleNode(string.Format("Control[@Name='{0}']", sName));
      if (node != null)
      {
      strText = node.Attributes["Content"].Value;
      }
    
      return strText;
     }
    
     private void LoadXML()
     {
      string strFile = File.xml";
    
      try
      {
      doc = new XmlDocument();
      doc.Load(strFile);
      
      
      }
      catch (Exception ex)
      {
      MessageBox.Show(ex.Message);
      }
     }
    
    my XMAL looks like this:
     <StackPanel x:Name="spTest">
      <Button x:Name="btnTest"></Button>
      <TextBlock Name="txtTest"></TextBlock>
     </StackPanel>
    

    and my File:

    <?xml version="1.0" encoding="utf-8" ?>
    <Controls>
     <Control id="1" Name="txtTest" Content="Welcome!" />
     <Control id="2" Name="btnTest" Content="Install" />
     <Control id="3" Name="spTest" Content="Stackpanel" />
    </Controls>

    • Proposed as answer by Stef S Tuesday, January 18, 2011 1:49 PM
    Tuesday, January 18, 2011 1:48 PM
  • If i have a combo box controlling the xml file i load?

    like

    Comboboxitem->XML1
    Comboboxitem->XML2

     

    Both XML have the same fformat of control id name, but with a different content

    Tuesday, January 18, 2011 2:19 PM
  • you can hold the XMLFile - Name in the ComboxItem and after changing the value you ahve to load the new content.
    Tuesday, January 18, 2011 2:26 PM
  • so at the comboboxitem_selected event handler i can put 
    private void LoadXML()
    {
      string strFile = File.xml";

      try
      {
      doc = new XmlDocument();
      doc.Load(strFile);
     
     
      }
      catch (Exception ex)
      {
      MessageBox.Show(ex.Message);
      }
    }

    this content in to load the different xml?
    Tuesday, January 18, 2011 11:33 PM
  • that's correct. You can call in the comboboxitem_selected event handler the method LoadXML() and after GetTextFromControl()
    Wednesday, January 19, 2011 5:30 AM
  • and also, if my application has multieple windows in 1 application

    Like when i press next, it close the current and switch to the next window, will do i need to code it in or it will have the current loaded xml?

    Wednesday, January 19, 2011 9:29 AM
  • If you have the file loaded in the Main-Window you can set a property to Access it from every other window.

    Wednesday, January 19, 2011 10:19 AM
  • sorry to trouble you, but how do i set the property?;x
    Wednesday, January 19, 2011 3:28 PM
  • You have to write some code yourself... :)

    Please mark my Answers if they sovled some pieces of your problems.

    Wednesday, January 19, 2011 3:50 PM
  • any clue?x.X
    Thursday, January 20, 2011 1:18 AM
  • i have an error at the C# coding where

    the doc

    the name 'doc' does not exist in the current context
    Thursday, January 20, 2011 1:27 AM
  • have somehow solved the problem on the doc, but i don't know why when i select the combo box, it doesn't load the content onto the button/ textblock

     

     

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    using System.Net;
    using System.IO;
    using System.Xml;
    
    namespace WpfApplication4
    {
    	/// <summary>
    	/// Interaction logic for MainWindow.xaml
    	/// </summary>
    	public partial class MainWindow : Window
    	{
    		public MainWindow()
    		{
    			this.InitializeComponent();
    
                LoadXML();
     GetTextForControl();
    
    			// Insert code required on object creation below this point.
    		}
    
        private void LoadXML()
      {
       string strFile = @"C:\Documents and Settings\081950G\Desktop\FYP\Japan.xml";
    
       try
       {
        XmlDocument doc = new XmlDocument();
        doc.Load(strFile);
    
        XmlElement root = doc.DocumentElement;
        
    
        foreach (XmlNode node in root.ChildNodes)
        {
         Console.WriteLine(node.Attributes["Type"].Value);
         Console.WriteLine(node.Attributes["Name"].Value);
         Console.WriteLine(node.Attributes["Content"].Value);     
        }
       }
       catch (Exception ex)
       {
        MessageBox.Show(ex.Message);
       }
        }
        
    
       private void Japan_Selected(object sender, RoutedEventArgs e){
        
           private void GetTextForControl()
     {
     foreach (UIElement element in spTest.Children)
     {
     if (element is Button)
     {
      ((Button)element).Content = FindTextForControl(((Button)element).Name);
     }
     if (element is TextBlock)
     {
      ((TextBlock)element).Text = FindTextForControl(((TextBlock)element).Name);
     }
     }
     }
    
     private string FindTextForControl(string sName)
     {
     string strText = string.Empty;
    
     XmlNode node = doc.DocumentElement.SelectSingleNode(string.Format("Control[@Name='{0}']", sName));
     if (node != null)
      
     strText = node.Attributes["Content"].Value;
     }
    
     return strText;
     }
    
     private void LoadXML()
     {
     string strFile = "Japan.xml";
    
     try
     {
     doc = new XmlDocument();
     doc.Load(strFile);
     
     
     }
     catch (Exception ex)
     {
     MessageBox.Show(ex.Message);
     }
     
    
    }
    
    

    Thursday, January 20, 2011 2:37 AM
  • is it possible to upload a sample file
    Thursday, January 20, 2011 4:28 AM
  • up, still unable to solve
    Tuesday, January 25, 2011 1:07 AM