C#-YAXLib:将数据导出到XML文件

时间:2018-11-29 11:47:18

标签: c# xml xml-serialization yaxlib

我有两个示例类,用于在测试中反序列化XML文件。

XmlExampleBasicUnit.cs

[YAXSerializeAs("Unit")]
public class XmlExampleBasicUnit
{
    [YAXSerializeAs("StringVar")]
    public String StringVar { get; set; }
    [YAXSerializeAs("Int32Var")]
    public Int32 Int32Var { get; set; }
    [YAXSerializeAs("DoubleVar")]
    public Double DoubleVar { get; set; }
    [YAXSerializeAs("DateTimeVar")]
    public String DateTimeVar { get; set; }
    [YAXSerializeAs("CharVar")]
    public String CharVar { get; set; }
}

XmlExampleCollectionOfUnits.cs

[YAXSerializeAs("CollectionOfUnits")]
public class XmlExampleCollectionOfUnits
{
    [YAXSerializeAs("Units")]
    public List<XmlExampleBasicUnit> Units { get; set; }

    public XmlExampleCollectionOfUnits(List<XmlExampleBasicUnit> units)
    {
        Units = units;
    }

    public XmlExampleCollectionOfUnits()
    {
    }
}

我想将变量XmlExampleCollectionOfUnits导出到一个格式正确的XML文件中。这是当前负责此功能的函数:

public void Export<T>(String fileName, T result) where T : class
{
    YAXSerializer serializer = new YAXSerializer(typeof(T));
    using (FileStream fs = File.Create(fileName))
    {
        Byte[] info = new UTF8Encoding(true).GetBytes(serializer.Serialize(result));
        fs.Write(info, 0, info.Length);
    }
}

问题是这正在使用GetBytes()函数,该函数添加了一些负责从XML文件导入数据的函数无法识别的字节。我一直在尝试用XmlTextWriter解决这个问题,但没有成功。我可以获得要写入文件的内容的String,但是XmlTextWriter无法处理。

1 个答案:

答案 0 :(得分:0)

Serialize的函数YAXSerializer对于XmlWriter具有重载。