Parsing Xml Data

Started by
2 comments, last by Spidi 7 years, 9 months ago

Hello, I have been trying to parse specific XML data using C#. I'm just going to post these screenshots and let you guys observe what may not be obvious to me.

Here is my XML File:

[attachment=32602:Screenshot 2016-07-15 18.25.22.png]

Here is the Enemy Class:

[attachment=32603:Screenshot 2016-07-15 18.25.33.png]

Here is the Running program:

[attachment=32604:Screenshot 2016-07-15 18.25.40.png]

The issue is that the XmlReader object will read through the file and reset the attributes. How can this be fixed so that the XmlReader will stop reading once it has no more relevant data? Thank you in advance!

Advertisement
ReadToDescendant: You could use the return value to stop when no more descendants with that name are found.

GetAttribute: Make sure the return value isn't null.

int.TryParse: Use the return value to find out if the parse succeeded.


Alternatively you could use reflection-based serialization, which I personally like better:

https://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.110).aspx

Thank you for the help. I tried all three of those methods and realized that the only reason the data was being changed was because the reader read the document three times and included whitespace in its reading. This caused variables to be set incorrectly and to null values. I ultimately solved it with a simple check to make sure that the reader only altered attributes when set to a specific node. Thank you again for your insight! :D

EDIT: Might give the reflection-based serialization a quick study :P

Hi jazzyspazglobal!

First: +1 for Nypyren, do check out the XmlSerializer class, since it will make your life so much more easier (by using it usually you don't even need to write any XML parsing code!).
Second:
Using an XmlReader implementation (like XmlTextReader in your case) is still a valid route, and can be used in combination with the XmlSerialzier for bigger control over parsing.
In your case specifically check out the XmlReaderSettings class. With this you can setup your reader (Settings property of the reader) to omit comment and white-space nodes from the XML file by setting the IgnoreComments and IgnoreWhitespace properties to true. This is common practice, since most of the time you are not interested in the white-space nodes used for formatting/prettifying the XML file nor for the comments :).

+ For using an XmlReader implementation + the reader settings, the more clean and advised method for construction is the static Create methods of the XmlReader class, instead of instantiating a concrete reader.

Br.

Blog | Overburdened | KREEP | Memorynth | @blindmessiah777 Magic Item Tech+30% Enhanced GameDev

This topic is closed to new replies.

Advertisement