После сериализации некоторых наборов данных в XML и обратно в мое приложение и последующего отображения в моем графическом интерфейсе я получаю какой-то странный выводимый XML, который, как я подозреваю, как-то связан с моими атрибутами, но яне уверен.Это приводит к выводу на мой пользовательский интерфейс, что является неблагоприятным.Я попытался очистить пост-сериализацию кода XML, но проблема сохраняется при следующей загрузке программы, что очень странно.
В некоторых случаях моя программа сериализует 3 массива, которые содержат строковые данные исохраняет их как XML.
После загрузки программы приложение десериализует 3 отдельных файла XML и передает строковые значения в некоторые пользовательские элементы управления, а именно в свойства «Content» некоторых кнопок.
Мои свойства для сериализации:
/// <summary>
/// A public accessor to access the private tasks' name field.
/// </summary>
[XmlAttribute]
public string[] TaskName
{
get
{
this.TaskName = this.taskNameArray;
return this.taskNameArray;
}
set
{
this.taskNameArray = value;
}
}
/// <summary>
/// A public accessor to access the private tasks field.
/// </summary>
[XmlAttribute]
public string[] TasksBody
{
get
{
this.TasksBody = this.tasksArray;
return this.tasksArray;
}
set
{
this.tasksArray = value;
}
}
/// <summary>
/// A public accessor to access the private task category field.
/// </summary>
[XmlAttribute]
public string[] TasksCategory
{
get
{
this.TasksCategory = this.tasksCategoryArray;
return this.tasksCategoryArray;
}
set
{
this.tasksCategoryArray = value;
}
}
и пример вывода XML:
<?xml version="1.0"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Ahn Jung Jae</string>
<string> &amp;lt;string&amp;gt;NONE&amp;lt;/string&amp;gt;
</string>
<string> &amp;lt;string&amp;gt;NONE&amp;lt;/string&amp;gt;
</string>
<string> &amp;lt;string&amp;gt;NONE&amp;lt;/string&amp;gt;
</string>
Я попытался выполнить некоторую очистку XML после сериализации с помощью ToString().SubString()
,но проблема сохраняется после перезагрузки программы.Любая идея о предотвращении странного XML будет принята с благодарностью.
ОБНОВЛЕНИЕ: Ниже приведен дополнительный код в моей программе, чтобы помочь дать некоторый контекст, как было запрошено. У меня есть два основных класса в программе mt: MainWindow.cs и Tasks.cs -
Этот метод ниженаходится в классе Tasks.cs и заполняет свойства массива:
/// <summary>
/// This method assigns the passed information of the tasks to their respective arrays.
/// </summary>
public void AssignParametersToArray(bool update)
{
// Assign parameters to array field values.
// There needs to be an index that keeps track of the latest number of task entries,
// as entries are: listed in an array, so lack the 'Add' function and
// entries are updated at run-time, dynamically, so an inherent loop would not work.
// If there are no elements in the specified slot of the array,
// then the array slot is free to be populated.
if (update == false)
{
for (int x = 0; x < this.TasksBody.Length; x++)
{
if (String.IsNullOrEmpty(this.tasksArray[x]))
{
// Task Body
this.tasksArray[x] = this.tasks;
this.TasksBody[x] = this.tasksArray[x];//[this.TasksBodyCounterProperty]; // This step should update automatically via an event, eventually.
this.TasksBodyCounterProperty++;
}
if (String.IsNullOrEmpty(this.tasksCategoryArray[x]))
{
// Task Category.
this.tasksCategoryArray[x] = this.tasksCategory;
this.TasksCategory[x] = this.tasksCategoryArray[x]; // This step should update automatically via an event, eventually.
this.TasksCategoryCounterProperty++;
}
if (String.IsNullOrEmpty(this.taskNameArray[x]))
{
// Task Names.
this.taskNameArray[x] = this.taskName;
this.TaskName[x] = this.taskNameArray[x]; // This step should update automatically via an event, eventually.
this.TasksNameCounterProperty++;
break;
}
}
}
}
Эти методы также находятся в классе Tasks.cs.Это процедуры сериализации и десериализации:
/// <summary>
/// This function serializes all the task information into an XML document.
/// </summary>
/// <typeparam name="T">This signifies the object type. For this routine, parameters are of type string.</typeparam>
/// <param name="taskBody">Parameter that holds the array that holds all the task body content.</param>
/// <param name="taskCategory">Parameter that holds the array that holds all the task category content.</param>
/// <param name="taskName">Parameter that holds the array that holds all the task name content.</param>
/// <param name="taskCategoryFilePath">The filepath upon which to create the destination for file category XML file.</param>
/// <param name="taskNameFilePath">The filepath upon which to create the destination for file name XML file.</param>
/// <param name="taskBodyFilePath">The filepath upon which to create the destination for file body XML file.</param>
private void Serialize<T>(string[] taskBody, string[] taskCategory, string[] taskName, string taskCategoryFilePath, string taskNameFilePath, string taskBodyFilePath)
{
// Create 3 seperate memory streams, one for each
// file destination of the tasks.
MemoryStream stream1 = new MemoryStream();
MemoryStream stream2 = new MemoryStream();
MemoryStream stream3 = new MemoryStream();
// Create an XML document and serializer object.
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(this.TasksBody.GetType());
// Loop through this functionality 3 times,
// recursively serializing task category, name and body arrays.
for (int i = 0; i < 3; i++)
{
try
{
// Switch-Case through index values, writing to each respective stream for
// the relevant task content.
switch (i)
{
case 0:
serializer.Serialize(stream1, this.TasksCategory);
stream1.Position = 0;
xmlDocument.Load(stream1);
break;
case 1:
serializer.Serialize(stream2, this.TaskName);
stream2.Position = 0;
xmlDocument.Load(stream2);
break;
case 2:
serializer.Serialize(stream3, this.TasksBody);
stream3.Position = 0;
xmlDocument.Load(stream3);
break;
}
switch (i)
{
case 0:
xmlDocument.Save(taskCategoryFilePath);
stream1.Flush();
break;
case 1:
xmlDocument.Save(taskNameFilePath);
stream2.Flush();
break;
case 2:
xmlDocument.Save(taskBodyFilePath);
stream3.Flush();
break;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
break;
}
}
}
public void Deserialize<T>()
{
this.tasks = string.Empty;
// Create 3 seperate memory streams, one for each
// file destination of the tasks.
MemoryStream stream1 = new MemoryStream();
MemoryStream stream2 = new MemoryStream();
MemoryStream stream3 = new MemoryStream();
T returnObject = default(T);
// Locate the target file path of the XML files storing the task information.
string taskCategoryFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory).ToString() + "taskCategory.txt";
string taskNameFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory).ToString() + "taskName.txt";
string taskBodyFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory).ToString() + "taskBody.txt";
// Define a limit for the following loop.
int taskTypeIndex = 3;
// Define a buffer to hold a filepath.
string filePathBuffer = string.Empty;
// Loop three times, deserializing the data in each XML file.
for (int i = 0; i < taskTypeIndex; i++)
{
try
{
if (i == 0)
{
filePathBuffer = taskCategoryFilePath;
}
else if (i == 1)
{
filePathBuffer = taskNameFilePath;
}
else if (i == 2)
{
filePathBuffer = taskBodyFilePath;
}
using (StreamReader reader = new StreamReader(filePathBuffer))
{
// Declare a new Xml Document and Serializer object.
XmlDocument document = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(this.tasks.GetType());//this.TasksCategory.GetType());
//StreamReader streamReader = new StreamReader(filePathBuffer);
//XmlReader xmlReader = new XmlReader();
// Assign the deserialized inforamtion to the respective
// properties.
if (i == 0)
{
//XElement root = XDocument.Load(stream1).Root;
//serializer.Deserialize(streamReader, "UTF-8"); //(stream1, this.TasksCategory);
for (int x = 0; x < 100; x++)
{
//if (reader.ReadLine() != "NIL")
//{
this.TasksCategory[x] = reader.ReadLine();
///}
//else
//{
// break;
//}
}
//serializer.Deserialize(stream1);
//stream1.Position = 0;
document.Load(filePathBuffer);
stream1.Flush();
//foreach (string item in this.TasksCategory)
//this.TasksCategory = (string)serializer.Deserialize(streamReader);
//item = (string)serializer.Deserialize(streamReader);
//serializer.Serialize(stream1, this.TasksCategory);
//stream1.Position = 0;
//xmlDocument.Load(stream1);
}
else if (i == 1)
{
for (int x = 0; x < 100; x++)
{
//if (reader.ReadLine() != " <string>NIL</string>")
//{
this.TaskName[x] = reader.ReadLine();
//}
//else
//{
// break;
//}
}
//serializer.Deserialize(stream2);
//stream2.Position = 0;
document.Load(filePathBuffer);
stream2.Flush();
}
else if (i == 2)
{
for (int x = 0; x < 100; x++)
{
//if (reader.ReadLine() != "NIL" || reader.ReadLine() != " < string > < string> NIL & lt;/ string & gt;</ string >" || reader.ReadLine() != " <string>NIL</string>")
//{
this.TasksBody[x] = reader.ReadLine();
///}
//else
////{
// break;
//}
}
//serializer.Deserialize(stream3);
//stream3.Position = 0;
document.Load(filePathBuffer);
stream3.Flush();
}
//returnObject = (T)serializer.Deserialize(streamReader); //
reader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("There was an error loading the tasks:" + ex.ToString());
}
this.CleanUpXML();
}
}
Есть пара комментариев, которые я оставил для личного пользования.Если вам нужна дополнительная информация, пожалуйста, дайте мне знать, или если что-то неясно с моим кодом.
Кроме того, я написал метод AssignParametersToArray () довольно давно, и я уверен, что качество кода можетБыть улучшенным - я оставил это там в этом посте, только если он подчеркивает, где я, возможно, ошибаюсь.