XmlSerializer插入2个xml声明
本文关键字:声明 xml 2个 插入 XmlSerializer | 更新日期: 2023-09-27 18:07:33
我正在编写一些代码来序列化一些体素模型数据。序列化器代码工作得很好,除了它插入了3个xml声明,这会在试图反序列化时导致错误。
我代码:static Encoding encoding = new UTF8Encoding(false);
public void Save(string path) {
/* trick to remove unessessarynamespace attributes */
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
var serializer = new XmlSerializer(typeof(VoxelData));
var stream = new StreamWriter(path, false, encoding);
serializer.Serialize(stream, this, ns); // this refers to the VoxelData class
/* converts a dictionary to an array of a temporary serializable type */
if (voxels != null) {
System.Type[] otherTypes = { typeof(Vector3Serializer) };
var attrSerializer = new XmlSerializer(typeof(voxelsave[]), null, otherTypes, new XmlRootAttribute() { ElementName="voxels" }, ""); // new XmlRootAttribute() { ElementName = "attributes" }, );
voxelsave[] voxelSave = voxels.Select(kv => new voxelsave() { data = kv.Value, position = new Vector3Serializer(kv.Key) }).ToArray();
attrSerializer.Serialize(stream, voxelSave, ns);
}
/* converts a dictionary to an array of a temporary serializable type */
if (attributes != null) {
System.Type[] otherTypes = { typeof(Vector3Serializer) };
var attrSerializer = new XmlSerializer(typeof(attributesave[]), null, otherTypes, new XmlRootAttribute() { ElementName = "attributes" }, ""); // new XmlRootAttribute() { ElementName = "attributes" }, );
attributesave[] attributeSave = attributes.Select(kv => new attributesave() { key = kv.Key, value = kv.Value }).ToArray();
attrSerializer.Serialize(stream, attributeSave, ns);
}
stream.Close();
}
以及一些序列化类的片段:
[XmlType(TypeName = "attribute")]
public class attributesave {
[XmlAttribute]
public object key;
public object value;
}
[XmlType(TypeName = "voxel")]
public class voxelsave {
public Vector3Serializer position;
public Voxel data;
}
[System.Serializable]
public class VoxelData {
[XmlIgnore]
private Dictionary<Vector3, Voxel> voxels = new Dictionary<Vector3, Voxel>();
[XmlIgnore]
public Dictionary<object, object> attributes = new Dictionary<object, object>();
[XmlAttribute("scale")]
public float scale = 1.0f;
...
}
下面是一个输出示例:
<?xml version="1.0" encoding="utf-8"?>
<VoxelData scale="1" />
<?xml version="1.0" encoding="utf-8"?>
<voxels>
<voxel>
<position x="0" y="0" z="0" />
<data color="RGBA(1.000, 0.000, 0.000, 1.000)" scale="1" />
</voxel>
</voxels><?xml version="1.0" encoding="utf-8"?>
<attributes>
<attribute key="handle">
<value d3p1:type="vector3" x="0" y="0" z="0" xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance" />
</attribute>
</attributes>
你可以看到有3个xml?
标签,其中2个不应该在那里。它们在试图反序列化时抛出错误,如果我删除第二个标签,它们反序列化很好。
我的问题是:为什么要插入第二个标签,我如何阻止它?
正如评论中提到的,您所面临的挑战可以通过向2个额外的XML序列化器添加额外的XmlWriterSettings来解决。
一个示例是:
var attrSerializer = new XmlSerializer(
typeof(voxelsave[])
, new XmlWriterSettings {OmitXmlDeclaration = true}
, ....)
很高兴有帮助!!