【发布时间】:2018-10-30 11:02:30
【问题描述】:
我目前正在生成用于配置服务器的 XML 文件。
我有一个使用 xsd 生成的类,其中包含 System.Xml.XmlElement 类型的属性。
public class GeneratedClass
{
...
private System.Xml.XmlElement informationField;
[System.Xml.Serialization.XmlArrayItemAttribute("Information", IsNullable=false)]
public System.Xml.XmlElement Information {
get {
return this.informationField;
}
set {
this.informationField = value;
}
}
...
}
我在将自定义对象“注入”到此信息属性时遇到了麻烦。
public class MyExampleObject
{
public string Name { get; set; }
public string Id { get; set;
}
程序反序列化一个GeneratedClass 类型的xml 文件,然后我想将MyExampleObject 添加到Informations 属性中。
我目前的做法是用这个方法:
XmlDocument doc = new XmlDocument();
using (XmlWriter writer = doc.CreateNavigator().AppendChild())
{
XmlSerializer serializer = new XmlSerializer(typeof(MyExampleObject));
serializer.Serialize(writer, MyObject);
}
this.Information = doc.DocumentElement;
在此之后,我将整个对象序列化为文件,但是当我这样做时,我得到了不需要的 xml 命名空间属性。
<Information xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="">
我发现其他有类似问题的帖子,但建议的解决方案给我留下了<Information xmlns="">,这仍然不是一个完整的解决方案。
我觉得可能有其他方法可以做到这一点,但我不确定如何。
有什么建议吗?
【问题讨论】: