-1

我正在尝试使用以下代码将数据保存为 xml

 StorageFile file = await dataFolder.CreateFileAsync(filename,
        CreationCollisionOption.OpenIfExists);

        // Serialize the object
        XmlSerializer serializer = new XmlSerializer(obj.GetType());

        // Write the data from the textbox.
        using (var s = await file.OpenStreamForWriteAsync())
        {
            try
            {
                s.Position = s.Seek(0, SeekOrigin.End);
                serializer.Serialize(s, obj);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
            finally{
                s.Close();
            }
        }

这会生成格式为 xml 的 xml:

<?xml version="1.0" encoding="utf-8"?>
<Tasks xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Task>task1</Task>
  <Group>group</Group>
  ....
</Tasks>

问题
我附加到文件时,我得到了这样的东西

<?xml version="1.0" encoding="utf-8"?>
<Tasks xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Task>task1</Task>
  <Group>group</Group>
  ....
</Tasks><?xml version="1.0" encoding="utf-8"?>
<Tasks xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Task>task2</Task>
  <Group>group</Group>
  ....
</Tasks>  

这可以防止数据被反序列化,如何避免写入元数据?

4

1 回答 1

2

您应该使用XmlTextWriterXmlTextWriter 类)来更好地控制 XML。请尝试以下方法:

    StorageFile file = await dataFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

    // Serialize the object
    XmlSerializer serializer = new XmlSerializer(obj.GetType());

    // Write the data from the textbox.
    using (var s = await file.OpenStreamForWriteAsync())
    {
        try
        {
            s.Position = s.Seek(0, SeekOrigin.End);

            using (var x = XmlWriter.Create(s, new XmlWriterSettings(){OmitXmlDeclaration = true}))
            {
                x.Setting.OmitXmlDeclaration = true;
                serializer.Serialize(x, obj);
            }
        }
        catch (Exception ex)
        {
            Console.Out.WriteLine(ex.Message);
        }
        finally{
            s.Close();
        }
    }

编辑:替换new XmlTextWriterXmlWriter.Create

于 2013-11-12T03:56:11.767 回答