Lesson 34: Learning to read XML files with the XmlNodes class in #C

The XMLDocuments class was used to read the XML file in the previous lecture. Enroll in a new class at The class XmlNodes, which is required for parsing and reading XML files, was introduced in the previous lesson’s example.

XmlNodes

In generally, an XML file is parsed into an XmlNodes, which is the file’s root element, and then into the childNodes property, which allows you to access the main element’s child elements.


Also, the XmlNodes class allows access to many other information such as name tags or name tag properties Or attributes, the text inside the tags or text inside also gives us the existence of the XML structure.


In this lesson, we are going to give a brief overview of some of the interesting aspects of the XmlNode class, because Having information about XmlNode as one of the key aspects when reading XML files by The XMLDocument class is very important.

In the examples in this lesson, we will use the DocumentElement element a lot, and since this element It is of the XMLElement type and XMLElement itself is inherited from the XmlNode class, in fact this type Friendships are almost the same.
The Property Name property simply declares the name of the element or node. For example, the code output is below the value “User” will be:

XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml (” A user node “);
Console.WriteLine (xmlDoc.DocumentElement.Name);
Console.ReadKey ();


The Property InnerText property also extracts the text between the open and closed tags of each tag, as in the following code:


XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml (” InnerText is here “);
Console.WriteLine (xmlDoc.DocumentElement.InnerText);
Console.ReadKey ();

The InnerXml property is slightly similar to the InnerText property, but while the InnerText property does not Removes the XML that is inside, property InnerXml explicitly does not do this.

Example The following shows the difference:


XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml (” InnerText / InnerXml is here “);
Console.WriteLine (“InnerXml:” + xmlDoc.DocumentElement.InnerXml);
Console.WriteLine (“InnerText:” + xmlDoc.DocumentElement.InnerText);
Console.ReadKey ():

The Property OuterXml property works the same as InnerText, except that in addition to the XML code Their text also shows.

The following code can show the difference between the two properties:
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml (” InnerText / InnerXml is here “);
Console.WriteLine (“InnerXml:” + xmlDoc.DocumentElement.InnerXml);
Console.WriteLine (“OuterXml:” + xmlDoc.DocumentElement.OuterXml);
Console.ReadKey ();


In the following example code, we also worked with the properties or attributes of the tags:


XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.LoadXml (” “);
if (xmlDoc.DocumentElement.Attributes [“name”]! = null)
Console.WriteLine (xmlDoc.DocumentElement.Attributes [“name”]. Value);
if (xmlDoc.DocumentElement.Attributes [“age”]! = null)
Console.WriteLine (xmlDoc.DocumentElement.Attributes [“age”]. Value);
Console.ReadKey ();

Lesson 33 Tutorial on XML Files with XmlDocument in #C Language

The XmlDocument takes up more memory than the Xmlreader Class, as we discussed in the last session. It’s being devoured and moving more slowly than it should.

However, there are a few advantages to working with the XmlDocument Class. It is simpler and requires less coding in certain circumstances.

XmlDocument


By using a tree approach (Hierarchical (evaluated, just as in the structure of XML files where each element has a name and a value), you may access the information within the file as soon as you read the contents. It’s possible for each kid to have a number of children’s elements, and each child may have many children’s elements.


In the previous lesson, we read information from an XML file for the European Central Bank that about exchange rates and Their changes provide data. In this lesson we will do this, but by using Xmlreader Class instead of XMLreader.


The XML file information can be received from the +lesson address and the data we need in the element <cube <cube. The tree structure of the xml file is the same as the code below:

< gesmes:Envelope >
 [other child nodes]
 < Cube >
 < Cube time="2011-04-12" >
 < Cube currency="USD" rate="1.4470"/ >
 < Cube currency="JPY" rate="121.87"/ >
 …

Element <Envelope: Gesmes is the file or Element root of the file, which can be used by property Documentele had access to it.


In the next step, we can use the Collection Childnodes property to the elements of the main element Get access.

In the example of this lesson, we intend to go to the elements of the child in three categories or Level below Get access to the main element.

This can be done using the following practical example code, exactly the same What we did in the previous lesson with the Xmlreader Card:

using System;
using System.Text;
using System.Xml;
namespace ParsingXml
{
 class Program
 {
 static void Main(string[] args)
 {
 XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.Load("www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
 foreach(XmlNode xmlNode in
xmlDoc.DocumentElement.ChildNodes[2].ChildNodes[0].ChildNodes)
 Console.WriteLine(xmlNode.Attributes["currency"].Value + ": " +
xmlNode.Attributes["rate"].Value);
 Console.ReadKey();
 }
99
 }
}

As you can see in the example code, we to the nodes cube element by going lower than the tree structure Hierarchy Childnodes have access Of the original file element called docuceteloment, The third child of the Node Child’s child (with zero -based index (we’ve got it.

Then follow the first child This element or node child is made and finally all elements of this child’s nodes child of collection We have requested.


Obviously the above code is used because we are familiar with the XML file structure and for the steps Next in the future is not very flexible.


Anyway, the way you will use an XML file depends a lot on the XML file source
And the kind of information you are looking for.


The example of this lesson will only work if we have a limited amount of information but for the purposes The larger, we need to write a better code to increase the readability of the program.


Because we have a node or node called Rate Currency and we can go to two property or Properties access and print it in the output, the code is a good example like the previous lesson.

Lesson 32 Learning to read XML files with the XMLReader class in C#

There are generally 2 methods for reading XML files in C #: Class. xmlDocument Class. XMLReader The XMLDocument class reads the entire contents of an XML file and stores it in system memory. Then to you Allows easy scrolling back and forth within the XML file, even using XPath technology, Do your search or query on the file.

XMLReader


XMLReader class, faster and less memory consuming option on reading files Is XML. The XMLReader class lets you in at any time with just one element Move the contents of the XML file and read the values ​​at the same time, then go to the next element in the file.


By doing the above, it is obvious that the program takes up much less memory, because at any given moment only the amount Will retain the current element. Additionally, because you can manually set the amount of each Check value, you will have direct access to the values ​​you want and this will work very quickly Wet.


In this lesson, focus on working with the XMLReader class, and in the next lesson, teach the class
We will pay Class XMLDocument. For a practical tutorial, let’s work with a small example where an XML file contains exchange rates (We will read rates currency. For this purpose, use an XML file related to the European Central Bank we do. You can download this file and read it from your hard disk.

But in fact both classes XMLReader and XMLDocument class can fine-tune the contents of an XML file from one address The url on a remote server reads like local files and the example XML file can be accessed from + See the address, in the following example code, we will use part of this file:
using System;
using System.Text;
using System.Xml;
91
namespace ParsingXml
{
class Program
{
static void Main (string [] args)
{
XmlReader xmlReader = XmlReader.Create (“http://www.ecb.int/stats/eurofxref/eurofxrefdaily.xml”);
while (xmlReader.Read ())
{
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name ==
“Cube”))
{
if (xmlReader.HasAttributes)
Console.WriteLine (xmlReader.GetAttribute (“currency”) + “:” +
xmlReader.GetAttribute (“rate”));
}
}
Console.ReadKey ();
}
}
}

We first created a new version of the Class XMLReader class using the Create () method. This method can receive multiple overloads (parameter sets), but its simplest form is to send a url With the URL of the XML file you want to read. Inside the loop while loop, create the Read () method on the version We call the XMLReader class.

This loop brings the file reader or reader to the next element Moves the file and returns true to the search operation if there is another element Continue. With all the elements of the file and exporting the false value, the loop execution and reading of the file stoppe will be. Within the loop while loop you can find a variety of properties and methods Use the XMLReader class to access information about your current or desired element.


In the example above, first check the NodeType property to make sure the file has an element (tag) and
Also, is its name equal to “Cub” or not? As you can see in the example XML file, any exchange rate
(rate currency) has an element called the Cube tag and that’s exactly what we’re looking for. As soon as we find a Cube element, do a check format to see if our element has Attributes (yode or not) and then by the method () Attribute Get the value of the two properties “currency” and We read “rate”. Finally, we print the values ​​of the two properties in the output and move on to the next element.


The output of the above example code should be a list of available currencies and their rates. As you can see, the process was very simple. Of course this is mostly because we give information to We needed them in the order we read them, without having to do any special operations on them. in other words,
When we display the list of data as a sequential list. In the next lesson, to teach how to read the file
We will pay for XML using the Class XMLDocument class and you will see the difference.


Note: You should be aware that there are many ways to run the above code with bug fixes and
The program will issue an error or exception. Therefore, you should be prepared to manage potential errors, for For this purpose, go to the error management or exception training course in C # language

Learning to work with XML file in C# language

Learning to work with XML file in C# language: XML stands for Language Markup Enterable. XML fie language, Is a widespread and common format for transferring data, mostly because it is easy to Both humans and machines can be read and understood.


If you have ever written a site in HTML, XML will be very familiar to you, because in fact
XML is a more rigorous and advanced version of HTML. XML of tags (properties) (attributer (and values) and its general code structure is the same as the following example code:

As you can see in the example code above, XML is a convenient format for defining information
Most programming languages ​​have special classes and functions for working with XML. The C # language is the same It is one of those programming languages ​​that has a special class space or namespace to work with XML.


The name of this namespace in C # is the XML .System suite, which has almost the ability to work with various capabilities It has XML language.

The next lessons will examine the use of these ready-made classes in the C # language, also for
We will read and write information in XML

Lesson 31 Learning to work with Structs in C#

Structs are a weight light alternative to C# classes. The reason for this statement requires a bit of technical discussion, but if we want to summarize, examples are made. Class instances (on memory) are stored in a tree or heap structure, while Samples made from a Structs are stored as a stack.

Structs in C#


In addition, in the Structure structure as opposed to Classes, you do not work with a reference to a structure, but You have direct access to the sample made of structs. It also means that when you have one
You pass struct to the function as a parameter, it is sent as value by call, not by call We talked about the difference between this method in the lesson of sending parameters to complete C # language functions. Direction For more information, refer to the mentioned section.

Tip: When you want to show simpler data, it is better to use the structure, especially in
When you want to quantify many copies of them. There are many examples in the .NET framework where Microsoft uses a struct structure instead of classes.


Use, such as Point, Rectangle or struct Color objects. In the first step, show you a practical example of how to define and use structures, and then about We will talk about the limitations of using them instead of classes:

 static void Main(string[] args)
 {
 Car car;
 car = new Car("Blue");
 Console.WriteLine(car.Describe());
91
 car = new Car("Red");
 Console.WriteLine(car.Describe());
 Console.ReadKey();
 }
}
struct Car
{
 private string color;
 public Car(string color)
 {
 this.color = color;
 }
 public string Describe()
 {
 return "This car is " + Color;
 }
 public string Color
 {
 get { return color; }
92
 set { color = value; }
 }
}

If you look closely at the example, you will see that this is the same code as in the class introduction section We used C #, except that we used struct instead of class in the second part. This example to
It shows well how similar the two concepts are. But according to the explanation at the beginning of the lesson As we mentioned, how are these two concepts different?


First of all, fields in struct structures cannot be initialized, ie by text code The following code cannot be assigned to a member:


private string color = “Blue”; If you specify a constructor function for struct, you must specify all fields before exiting Constructor to be set. The struct itself has a default constructor function But if you want to manually specify the constructor function, you must specify all fields in the function definition Manufacturer, set the value. On the other hand this means that you can not make a constructor function without a parameter Specify for struct, but all constructor constructor functions must have at least one parameter.

In the code In the example above, we set a specific value for the color field, which if we did not do this, the compiler Issued an error. A struct can not be inherited from other classes or other structures (inherit) and classes can not inherit from inherit structures. Structs also support interfaces, which means that any
struct can implement its own interfaces.

Lesson 28 Learning to work with Enumeration in C#

Enumeration are a collection of named values that correspond to a set of numbers, and they are often of the integer type. Enumeration are useful in a variety of situations, such as when you need to quickly select a value from a set of fixed values and match it to a numeric value.


Enumeration are defined above the classes and inside the namespace, as seen in the practical examples code in this lecture. As a result, instead of the programme, you can use any Enumeration in the entire namespace.


The following code shows a simple example of defining Enumerations in C#: public enum Days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}.

All of the values in the Enumeration above have a numerical value. If the associated values are not explicitly set enumerations, the first value corresponds to o, the second value corresponds to 1, and so on.


The following code shows how to connect each of the Enumeration items by default and shows you how to use one Teaches a specific value in terms of an Enumeration:

using System;
namespace ConsoleApplication1
{
 public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
 class Program
 {
 static void Main(string[] args)
 {
 Days day = Days.Monday;
 Console.WriteLine((int)day);
 Console.ReadLine();
 }
 }
}

The output of the example code above will be zero, because the Monday value corresponds directly to the o value. Of course by The following code can change the number corresponding to the Enumerations to any value: public enum Days {Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
If you run the above code, you will see that this time Monday will correspond to one instead of zero.

Other values Enumeration will each have a value greater than 1, respectively. Tip: You can assign each Enumeration member to a specific number and not necessarily in a row.


Due to the direct relationship of each Enumeration member with its corresponding number, you can count the numbers of each member Read your desired enumeration. As the following code:

Days day = (Days) 5;
Console.WriteLine (day);
Console.ReadLine ();
Another feature of Enumerations is that with iterative loops, you can string values
Show an Enumeration in the output. Change the code of the previous example to the following code:
static void Main (string [] args)
{
  string [] values = Enum.GetNames (typeof (Days));
  foreach (string s in values)
  Console.WriteLine (s);

  Console.ReadLine ();
}
83
Class Enum has a set of application methods that you can use to work with Enumeration
Use.

Lesson 27 More Advanced Training with Breakpoint in Debug codes #c

Today is our lesson no 27 and today i will teach you about Lesson training with Breakpoint in Debug codes #c. We developed a simple Breakpoint in the previous courses. However, when working with Breakpoints, especially in the Visual Studio environment, there are many more options.

Of course, Microsoft appears to be involved. These capabilities have been deactivated in Visual Studio Express editions, although they are still available in the higher version.

Condition feature:

This Subject allows you to identify a condition, and when that condition is right or true, or its value changes, a Breakpoint is triggered. This capability is quite useful when working with higher-level code. For instance, if you want the software to stop running under particular circumstances.

For example, suppose you have a loop loop that will repeat several times before reaching the desired code.

In such circumstances you can by specifying a condition or Condition and adding it to Breakpoint, Control the conditions. We have created the following example to show the Condition feature:

static void Main(string[] args)
{
 for(int i = 0; i < 10; i++)
 Console.WriteLine("i is " + i);
}

Place t on the code line that displays the output on the confesole. Then the program perform it. Breakpoint occurs every time the ring is repeated. But that’s not what we follow Are.

May want Breakpoint only when I am equal to 4). The 5th time of the loop (active Become.

So add the condition 4 == I to Breakpoint.
Breakpoint is now shown with a white circle inside it and says that to run has a condition And it runs when the value of the variable I is 4.

You can also add the “Changed Has” option to tell Debugger only when The result changed, enable Breakpoint, an example when the value changed from True to False.

Ability:

Using the Count Hit feature you can set another condition for running Breakpoint
The number of times will Breakpoint occur in the code.

For example, you can decide that Breakpoint, a specified number of times in the unpublished code cause Run the program. There are different settings for the condition that you can get them in the time of work.

Change the program level.

: When Hit Ability

When Breakpoint arrives, this window can dictate how the application should behave. This is perhaps most useful when you don’t want the programme to terminate when it reaches Breakpoint, but instead want a specific message or a macro to run. This feature allows you to create a custom message in the application process and determine and print specified information. You can use Determine Macro to run the Breakpoint point as soon as the programme starts in more sophisticated scripts.

Lesson 26: Learning to work with the Window Tool in Visual Studio

Learning to work with the Window Tool in Visual Studio. Changed the bottom of the programme and new windows appear) regardless of whether you turn them off or not Activate new windows labelled “Locals”, “Watch”, “Strack Call”, and “Immediate” when doing code debugging in Visual Studio.

Window Tool in Visual Studio

“Window, which are related to Debugging operations. In this section, we will review each of the tools
the payment.

Locals window:

This is the most basic tool in this section. When the programme reaches a breakpoint, this window displays all Local code variables, allowing you to quickly inspect them. View details like name, kind, and amount. You can even type in the name of the variable you want to use. To give the selected variable a new value, click the table and select a “Value Edit” item. You can use this work to test programme codes in a variety of additional circumstances.

“Watch”, “Strack Call”

The Window Watch window is somewhat similar to the Locals window. With the difference that in this window you can Decide which variables to set as local or global.

you can Drag your desired variable to the location of the page code, or the Locals window, or write its name in the last blank line; Monitor and add to the Watch window. Watch list variables until you delete them The windows will remain, but their value will only be updated when you enter the code range associated with them Be.

For example, a variable belonging to function A will not be updated when you are inside the code of function B. Similar In the Locals window, you can right-click on the variable you want and select “Value Edit,” the value Change it.

: Call Stack window

The Stack Call window shows the hierarchy or execution of program functions. For example, if the function A Calls function B and function B calls function C, these communications can be found in the Call stack window Observe and jump on the code of each function if desired. You can also see what Parameters are passed to each function.

The example code of this lesson was very simple and you can easily see the navigation path of the function.

But in Large projects, understanding the order of execution of functions and parameters of each of them, it is necessary to stack Call Can be done.

The Window Immediate window can be the most useful Debug operation window. This window lets you Select the desired sections from the program code and run. You can also set values Check or change their variables.

Just type the code you want in the window and run it by pressing the Enter key. Name each variable
Type and print its value in the output. Change the value of your desired variable by writing 5 = a and the same See the moment of the result of the change in the code. The Window Immediate window is like a terminal in C #, to As soon as you write the code or change the program, you will see the output.

Lesson 25: Learning to move between codes when debugging C# Applications

We’ll teach you how to switch between codes when debugging C# applications in this lesson. I created a programme with the following code for this purpose:

namespace DebugTest
{
 class Program
 {
 static void Main(string[] args)
 {
 int a = 5;
 a = a * 2;
 a = a - 3;
 a = a * 6;
 Console.WriteLine(a);
21
 }
 }
}

The code in the example above performs various mathematical operations on a variable before printing the final result in the output. Slowly Insert a Breakpoint next to the first line where variable an is defined and quantified, as shown in the previous lesson.

The project should now be run. On the first line, you should run breakpoint. Moving the cursor over variable a will reveal its value. The variable a has the default value of the numeric variables, which is zero, because the code for that line has not yet been performed.

But let’s change the trend a bit.

From the Debug menu, select “over Step” or press the F10 key. In this case, the code line Next the program is executed and you can see by moving the mouse on the code that now the variable a has a value.

Press the F10 key again to move in the lines of code and run each line one by one and its variable value
Measure in that line, until you reach the end of the code.

The above example was very simple but at the same time practical, now we can enter the more advanced stages.

C

Note the following example:

namespace DebugTest
{
 class Program
 {
 static void Main(string[] args)
 {
22
 int a = 5;
 int b = 2;
 int result = MakeComplicatedCalculation(a, b);
 Console.WriteLine(result);
 }
 static int MakeComplicatedCalculation(int a, int b)
 {
 return a * b;
 }
 }
}

Put a breakpoint in the first line of the Main method and run it. Then, to move, hit the F10 key. Between programme lines and code execution, this is used.

As you can see, the software does not pay heed to the function call code. This is the Debugger assumption for the method mode Prediction. But, starting from the beginning, pick enter Step from the Debug menu, or hit the F11 shortcut key, when you reach the code line Call the Calculation Make ().

Press. At this point, the program enters the function call operation and scrolls the function body completely he does. So by pressing the F11 button, you can also check the execution of the program.
If you enter a function in the midst of a line, skip viewing the function’s continuation and move straight to the code. To return to the main programme, press F11 + shift or pick “out step” from the Debug menu. Press simultaneously.

In this situation, the software returns to the code after the function, allowing you to continue the code. After you want to call a function and then exit when it’s finished.

Lesson 24 Learning to use Points Break in Debugging C# Codes

This is our tutorial no 24 and today I will teach you about Points Break in Debugging C# Codes. The first thing you need to learn in the C# or Debugging code operation is to use BreakPoints.

Points Break in Debugging C# Codes

BreakPoints performs just as its name suggests. BreakPoint designates a point in your code where the compiler exits and the programme exits briefly. You can use this tool to double-check your code and the values of variables and expressions in the programme.


To use BreakPoint in a Visual Studio environment, right-click on the program’s side edge, aligned with the code you wish to debug, and the app will draw a red circle for you to position BreakPoint.

For a better understanding, copy the following code snippet into the Visual Studio environment and create a BreakPoint next to it.

namespace DebugTest
{
 class Program
 {
 static void Main(string[] args)
 {
 int a = 5, b = 8, c = 233;
 int d = a + c - b;
 Console.WriteLine(d);
 }
 }
}

The code in the example above is very simple, and you can even calculate the value of a variable at any time with a calculator Calculate and check your code. But in large projects, doing this manually is almost impossible Is.


Create a BreakPoint next to the code line shown in the image below:

VPN

You are now prepared to troubleshoot your first page in C #. Using the F5 key to start the software. The programme will proceed normally and according to schedule. The processing operation to check the code stops when it hits the breakpoint code line. In the code above,

The variables a, b and c have a value, but in the specified line the variable d has not been set yet and the value is prefixed. It has the assumption for integer, ie zero. After running this line of code that variable d is your new value Earns.


Now to the exciting part of the program, move the mouse over the names of different code variables. An open tooHip It tells you how much each variable has at that moment.

The variable d has a default value of zero until this line is run, as previously stated. However, by proceeding to run the application, its value can be altered. In the next session, we’ll learn how to browse through programme codes and focus on debugging activities.