有问题反序列化xml文件

时间:2017-06-28 09:07:46

标签: c# xml serialization uwp

我目前正在编写UWP应用程序,我遇到了反序列化xml文件的问题。

我成功使用此代码序列化对象

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();
    }
}

但是当我将对象序列化为xml时,它始终使用<?xml version="1.0" encoding="utf-8"?>和xmlns属性序列化我的对象。
我想删除所有xmlns属性并仅保留第一个xml标记。有可能吗?或者我应该尝试使用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>

反序列化的问题是由于xml标记<?xml version="1.0" encoding="utf-8"?>

而无法读取我的xml文件

这是我的反序列化代码

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;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您可以添加空命名空间和空值
请参阅我使用的C#扩展方法,例如:

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();
    }
}

您可以修改它以直接保存到文件中,例如。

有关反序列化,请参阅https://stackoverflow.com/a/3187539/194717

答案 1 :(得分:0)

如果您需要处理许多tabIndex个对象,请创建一个列表。

Personnne

创建的对象添加到此列表中。

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

序列化整个列表。在那时覆盖现有文件。

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

将文件中的数据反序列化到列表中。

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);
    }
}