- Home /
XmlException: Root element is missing when deserializing
I am trying to deserialize an xml file. My code is based on answers I've read, I googled for a solution end everyone keeps stating to check the xml to see if it has a root but I have no problem with this. This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<tips>
<tip>
All nutrition facts labels have the same format, with serving size and calories listed on top. Below this:
● List of essential nutrients including: total fat, cholesterol, sodium, potassium, total carbohydrates and finally protein.
● Below that: the essential nutrients, some vitamins and minerals.
● Finally, the ingredient list.
The serving size for the product helps you determine if you actually consume the amount listed as the serving size. For example, the serving size for ready-to-eat cereal is one cup. If you eat two cups of cereal, you would need to multiply the numbers on the nutrition facts label by two.
</tip>
<tip>
The total fat is important for determining what types of fat the product contains. Fats such as mono and polyunsaturated fats are more heart healthy fats while saturated and trans-fats are detrimental to overall health. The American Heart Association (AHA) recommends avoiding products that contain
any industrially manufactured trans-fat, meaning “partially hydrogenated oils”.
</tip>
</tips>
And here is my code to find and deserialize the file:
string absolute_path = Application.streamingAssetsPath + file_path + ".xml";
Debug.Log("This is the file path" + absolute_path);
WWW www = new WWW(absolute_path);
while (!www.isDone)
{
}
XmlSerializer serializer = new XmlSerializer(typeof(Tips));
MemoryStream stream = new MemoryStream(www.bytes);
if(stream != null)
{
Debug.Log("Stream is not null");
tips = serializer.Deserialize(stream) as Tips;
}
stream.Close();
This is the Tips class:
[XmlRoot("tips")]
public class Tips
{
[XmlElement("tip")]
public List<string> tip { get; set; }
}
Any help will be greatly appreciated :)
I forgot to add that I am running this code on my android device after installing the apk. The code run on my pc successfully but if I install the apk, the error I stated comes up.
Answer by Priyanka-Rajwanshi · Apr 20, 2020 at 06:36 PM
@Kirki_333 Try using StringReader.
filePath = Path.Combine(Application.persistentDataPath, "filename.xml");
if (File.Exists(loadedFile))
{
string text = File.ReadAllText(loadedFile);
XmlSerializer serializer = new XmlSerializer(typeof(Tips));
using (StringReader reader = new StringReader(text))
{
Tips tips = serializer.Deserialize(reader) as Tips;
}
}
For complete documentation of how to parse Xml, check this link.
I tried your code, now it gives me a null reference because it can't find the file. The variable loadedFile has this value jar:file:///data/app/com.$$anonymous$$tsa.Healthy_$$anonymous$$ev6-2/base.apk!/assets/understanding_nutrition_tips.xml
Should the path have that format?
use filePath = Path.Combine(Application.persistentDataPath, "filename.xml"); I have checked it in Android Phone and it works fine. I have updated original answer accordingly.
Answer by Bunny83 · Apr 20, 2020 at 03:05 PM
Well such issues are usually related to the actual data you're putting through the XmlSerializer. Note that the XmlSerializer does not really work well with BOMs at the front of your file. While most applications just ignore it or use it to interpret the byte order of the file, the XmlSerializer will choke on it. So when editing your xml file, make sure you save it without a byte order mark. Even it should be obvious it's generally recommended to save your file with utf8 since it is the text encoding that works best on all platforms.
If you're on windows and even using notepad to edit your xml file, just resave it and select UTF8 (without BOM) as the encoding and you shouldn't have any issues. Any notable text editor will allow you to omit a BOM.
If you get that file from somewhere else you may want to analyze the start of the byte stream manually and remove the BOM before feeding it to the serializer.
After reading your answer, I opened my xml file with Notepad++ and checked at the bottom right corner if it says UTF-8-BO$$anonymous$$ but it seems it is alright. It says it's UTF-8. Is there a possibility the BO$$anonymous$$ exists and is unrecognisable by a text editor? Also, I didn't get the file from somewhere, I created it myself.
The byte order mark is not a printable character. It's a control character that is used by text parsers to know the byte order used to encode the following text. For UTF8 this is completely useless since UTF8 is immune to different byte orders. However from the unicode point of view it's not explicitly forbidden to include a byte order mark, they actuall recommend to not including it as you can read here.
When you use Notepad++ you can change your encoding settings in the preferences. I quickly switched the language from german to english and made a screenshot:
Note that changing the preferences will not affect any file that already has a byte order mark. To remove it in Notepad++ you should use the format / encoding menu at the top. Note that you have to resave the file when you changed the format / encoding
This is the difference when I view my test file with a hex editor
Your answer
Follow this Question
Related Questions
XML Load unauthorized access 2 Answers
A node in a childnode? 1 Answer
Unity Crash - Access Violation (0xc0000005) error 1 Answer
XmlWriter.Create exception, "Could not find the file..." on Android 0 Answers
Can not reference System.Xml.Linq 3 Answers