Chưa phân loại

C++ tutorial – Parse a non-value XML attribute to int using XmlSerializer

In last post about C# Tutorial – XML Serialization, I showed you how to use XmlSerializer to parse XML data to Object in C#. And in this post, I don’t intend to rewrite that topic with C++/CLI because all of us know that both of languages are very similar. Instead, I’ll share you a tip to parse a non-value XML attribute to int (or any number data type) using XmlSerializer. So, what is a non-value attribute, I’ll explain bellow:

Now, We have an XML data like this:

<Score Math="10" History="9" Geography="8" />

And this is the Score model:

public ref class Score
	int Math;
	int History;
	int Geography;

We want to parse this data to Object in C++, everything is very simple, and we receive the result:

Math = 10;
History = 9;
Geography = 8;

Now, let’s change some thing in XML:

<Score Math="10" History="9" />

And here is result:

Math = 10;
History = 9;
Geography = 0;

As default, XmlSerializer will set default value for all empty attributes. The the default value based on programming language specification.

Now, if we change the XML like this:

<Score Math="10" History="" />

The History attribute has non-value. When we parse this data we will have an FormatException. Because “” is not an interger. ^^

To fix this problem, I have a solution as bellow:

String^ History_String;

property int History
	int get()
		int result;
		Int32::TryParse(History_String, result);
		return result;

As you can see, the solution here is very simple. First, we will parse XML data to a String variable (String will hold any data format). Then, we will create a property to encapsulation History field, and in its get method, we use Int32::TryParse to parse above String to Int. If the parsing succeeded, we have an actually value, otherwise, we have a default value (that is 0). And here is result:

Math = 10;
History = 0;
Geography = 0;

Hope this post will help you when you meet this case.

Happy coding!!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s