I am facing a problem while reading xml in C# linq to xml.
When I try to read xml document by using following statement:
XDocument xdoc = XDocument.Load(path);
It throws an exception like this.
Data at the root level is invalid. Line 1, position 1.
When I open the xml file that I was trying to read, I found an invalid character before xml declaration. Here is the declaration:
?<?xml version="1.0" encoding="utf-8"?>
I know the question mark at the start of declarations shouldn't be there.
I have three questions
1) How to read this invalid xml in C# linq to xml?
2) How to remove such kind of invalid characters any where in the xml in C#?
3) How to prevent these kind of invalid characters while creating the xml in c# linq to xml?
xml sample: ?<?
hex equivalent : 3f 3c 3f
And here is the code that I am using to create it:
XDocument xdoc = new XDocument();
xdoc.Add(new XElement("TaskAlert"));
AddParentNodeInTaskAlertXml(ref xdoc, userId);
and so on......
I couldn't understand the reason why it add such kind of characters sometime.
Here is some code that I am using to create or load the file:
public static void CreateUpdateTaskAlertXmlFile(int userId)
{
try
{
string path = string.Format("{0}\\{1}\\{2}", Application.StartupPath, "Configuration",
"TaskAlert.xml");
if (userId.Equals(0))
userId = Utility.Application.CurrentUser.UserId;
XDocument xdoc;
LoadTaskAlertXml(out xdoc, path, userId);
xdoc.Save(path);
}
catch (Exception exception)
{
MSLib.HandleException(exception);
}
}
public static void LoadTaskAlertXml(out XDocument xdoc, string path, int userId)
{
xdoc = null;
TaskCollection tasks = TaskEntity.GetOverDueTasks(userId);
if (!File.Exists(path))
{
CreateTaskAlertXml(userId.ToString(), ref xdoc);
AddOverDueTasksInTaskAlertXml(xdoc, userId.ToString(), tasks, false);
}
else
{
xdoc = XDocument.Load(path);
XElement userElement =
xdoc.Descendants("User").Where(x => x.Attribute("Id").Value.Equals(userId.ToString())).
SingleOrDefault();
if (userElement == null)
{
AddParentNodeInTaskAlertXml(ref xdoc, userId.ToString());
AddOverDueTasksInTaskAlertXml(xdoc, userId.ToString(), tasks, false);
}
else
AddOverDueTasksInTaskAlertXml(xdoc, userId.ToString(), tasks, true);
}
}