【问题标题】:having an issue deserializing an xml file反序列化 xml 文件时遇到问题
【发布时间】:2017-06-28 09:07:45
【问题描述】:

我目前正在编写 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 时,它总是使用 &lt;?xml version="1.0" encoding="utf-8"?&gt; 和 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标记&lt;?xml version="1.0" encoding="utf-8"?&gt;而无法读取我的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;
        }
    }
}

【问题讨论】:

    标签: c# xml serialization uwp


    【解决方案1】:

    如果您需要处理许多 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);
        }
    }
    

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

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

    【讨论】:

      【解决方案2】:

      您可以添加一个空的命名空间和空值
      请参阅我使用的这个 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

      【讨论】:

      • 感谢我尝试了它的序列化,它转换了字符串中的所有标记。现在正在尝试修复反序列化代码
      • 如果有用,请投票。修复反序列化代码需要什么帮助?
      • 尝试了你为反序列化提供的链接,它显示“xml 文档在第 1 行,位置 1 存在错误。根级别的数据无效。第 1 行,位置 1。”
      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多