0

I am currently programming a UWP application and I am having an issue deserializing an xml file.

I succedded serializing an object using this code

private async void button_Click(object sender, RoutedEventArgs e)
{
    Model.Personne user = new Model.Personne();
    {
        user.username = textBox.Text;
        user.password = p1.Password;
        user.email = textbox1.Text;
        user.address = textBox2.Text;
        var tracker = new Geolocator();
        tracker.DesiredAccuracyInMeters = 5;
        var position = await tracker.GetGeopositionAsync();
        user.Latitude = position.Coordinate.Latitude;
        user.Longitude = position.Coordinate.Longitude;
        user.doesExist = true;
    }
    await SaveToXml(user, "users.xml");

    this.Frame.Navigate(typeof(find_me));
}
public static async Task SaveToXml<T>(T user, string filename)
{
    if (user == null) { return; }

    try
    {
        XmlDocument xmlDocument = new XmlDocument();

        XmlSerializer serializer = new XmlSerializer(user.GetType());
        StorageFolder folder = ApplicationData.Current.LocalFolder;
        // StorageFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
        Stream stream = await folder.OpenStreamForWriteAsync(filename, CreationCollisionOption.OpenIfExists);
        using (MemoryStream str = new MemoryStream())
        {
            serializer.Serialize(stream, user);
            stream.Position = 0;
            xmlDocument.Load(stream);
            XmlNode node = xmlDocument.CreateElement("Personnes");
            xmlDocument.AppendChild(node);
            xmlDocument.Save(stream);
            stream.Dispose();
        }
    }
    catch (Exception ex)
    {
        ex.ToString();
    }
}

But when I serialize my object into xml it serializes my objects with always the <?xml version="1.0" encoding="utf-8"?> and xmlns attributes.
I want to delete all the xmlns attributes and keep only the first xml markup. Is it possible to do it? Or should I try serialize in JSON?

<?xml version="1.0" encoding="utf-8"?>
<Personne xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <username>toto</username>
  <password>tata</password>
  <email>titi</email>
  <address>teuteu</address>
  <Latitude>49.201083564616972</Latitude>
  <Longitude>-0.37977506716400489</Longitude>
  <doesExist>true</doesExist>
</Personne>
<?xml version="1.0" encoding="utf-8"?>
<Personne xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <username>aymann</username>
  <password>vierge</password>
  <email>a.blal@hotmail.fr</email>
  <address>97 rue des Borches</address>
  <Latitude>49.20236710462931</Latitude>
  <Longitude>-0.39321689482623645</Longitude>
  <doesExist>true</doesExist>
</Personne><?xml version="1.0" encoding="utf-8"?>
<Personne xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <username>asalfo</username>
  <password>lolo</password>
  <email>lolo</email>
  <address>lolo</address>
  <Latitude>49.202317469778862</Latitude>
  <Longitude>-0.39308322124621681</Longitude>
  <doesExist>true</doesExist>
</Personne><?xml version="1.0" encoding="utf-8"?>
<Personne xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <username>google</username>
  <password>google</password>
  <email>google</email>
  <address>google</address>
  <Latitude>49.202210566144032</Latitude>
  <Longitude>-0.39300312109158891</Longitude>
  <doesExist>true</doesExist>
</Personne><?xml version="1.0" encoding="utf-8"?>
<Personne xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <username>amadou</username>
  <password>dsfjsmlgkj</password>
  <email>sdklfjsdg</email>
  <address>mfsldkgmljg</address>
  <Latitude>49.202213601881432</Latitude>
  <Longitude>-0.39299270197801961</Longitude>
  <doesExist>true</doesExist>
</Personne>

And the issue for deserializing is that my xml file can't be read because of the xml markup <?xml version="1.0" encoding="utf-8"?>

Here is my deserialize code

public static async void reader()
{
    string filename = "users.xml";
    List<Model.Personne> users;
    StorageFolder folder = ApplicationData.Current.LocalFolder;
    Stream stream = await folder.OpenStreamForWriteAsync(filename, CreationCollisionOption.OpenIfExists);
    using (var reader = new StreamReader(stream))
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(List<Model.Personne>),
            new XmlRootAttribute("Personne"));
        users = (List<Model.Personne>)deserializer.Deserialize(reader);

        foreach (var user in users)
        {
            latitude = user.Latitude;
            longitude = user.Longitude;
        }
    }
}
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
aymannblal
  • 19
  • 5

2 Answers2

0

You can add an empty namespace and empty value
See this C# Extension Method that I use, for example:

public static string ToXMLString<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

    using (StringWriter textWriter = new StringWriter())
    {
        //Create our own namespaces for the output
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

        //Add an empty namespace and empty value
        //ns.Add("", "http://www.portalfiscal.inf.br/nfe");
        ns.Add("", "");

        xmlSerializer.Serialize(textWriter, toSerialize, ns);
        return textWriter.ToString();
    }
}

You can modify it to save directly to a file, for example.

For Deserialization, see See https://stackoverflow.com/a/3187539/194717

Tony
  • 16,527
  • 15
  • 80
  • 134
  • thanks i tried it for serialization, it convert all markups in strings .now trying to fix the deserialisation code – aymannblal Jun 28 '17 at 17:39
  • If useful, please vote up. What help you need to fix deserialisation code? – Tony Jun 28 '17 at 18:10
  • tried the link that u gave for deserializing it says "There was an error in xml document at line 1, Position 1 . The data at the root level is invalid. Line 1, position 1." – aymannblal Jun 29 '17 at 11:56
0

If you need to work with many Personnne objects then create a list.

List<Model.Personne> personneList = new List<Model.Personne>();

Created objects add to this list.

private void buttonAdd_Click(object sender, RoutedEventArgs e)
{
    var user = new Model.Personne();
    // set properties
    personneList.Add(user);
}

Serialize the whole list. At that overwrite the existing file.

private async void buttonSave_Click(object sender, RoutedEventArgs e)
{
    XmlSerializer serializer = new XmlSerializer(personneList.GetType());
    StorageFolder folder = ApplicationData.Current.LocalFolder;

    using (var stream = await folder.OpenStreamForWriteAsync("users.xml",
        CreationCollisionOption.ReplaceExisting))
    {
        serializer.Serialize(stream, personneList);
    }
}

Deserialize data from a file to the list.

private async void buttonLoad_Click(object sender, RoutedEventArgs e)
{
    XmlSerializer serializer = new XmlSerializer(personneList.GetType());
    StorageFolder folder = ApplicationData.Current.LocalFolder;

    using (var stream = await folder.OpenStreamForReadAsync("users.xml"))
    {
        personneList = (List<Model.Personne>)serializer.Deserialize(stream);
    }
}
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49