【问题标题】:XML serialization results in duplicate nodesXML 序列化导致重复节点
【发布时间】:2011-12-27 21:42:20
【问题描述】:

我有一个对象结构,我试图将其序列化为 xml,这会导致节点级别重复。我很确定它与子类化有关,因为我必须实现自己的反序列化,但我不确定另一个方向到底发生了什么。在应用程序启动时反序列化我的数据时使用相同的 xml 结构作为输入,就像重新序列化它以供以后保存时一样。

以下是错误输出 xml 的样子:

<Keyboarding xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Exercises>
    <Exercise>
      <Exercise Id="3" ActivityNumber="5" SubActivityNumber="b" Type="Standard">
        <Title>Test Title</Title>
        <Instructions>Downloaded Update Instructions</Instructions>
      </Exercise>
    </Exercise>
  </Exercises>
</Keyboarding>

它应该是这样的(初始反序列化时的样子):

<Keyboarding xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Exercises>
      <Exercise Id="3" ActivityNumber="5" SubActivityNumber="b" Type="Standard">
        <Title>Test Title</Title>
        <Instructions>Downloaded Update Instructions</Instructions>
      </Exercise>
  </Exercises>
</Keyboarding>

根对象包含一组练习。练习是我的基类,而子类由 Type 属性确定。我正在使用自定义 xml 序列化程序来构建来自练习的不同派生类型的对象,因为它允许我使用反射来匹配 2 打左右的潜在派生类型中的任何一个,这些类型在第一次读入时的顺序和数量未知通过我的申请。

这是根元素的集合,使用自定义的 xml 序列化器:

[XmlArray("Exercises")]
[XmlArrayItem("Exercise", Type = typeof (ExerciseXmlSerializer<Exercise>))]
public Collection<Exercise> UnprocessedExercises { get; set; }

我的基本练习类声明如下:

[Serializable]
[XmlType(AnonymousType = true)]
public class Exercise

我的派生类声明如下:

[Serializable]
[XmlType(AnonymousType = true)]
[XmlRoot(ElementName = "Exercise", IsNullable = false)]
public class StandardExercise : Exercise

这是我的自定义 xml 序列化程序的编写器部分:

public class ExerciseXmlSerializer<T> : IXmlSerializable where T : class
{
    private T _data;
    ...
    public void WriteXml(XmlWriter writer)
    {
        Type type = _data.GetType();

        new XmlSerializer(type).Serialize(writer, _data);
    }
    ...
}

在WriteXml() 方法中,类型变量被正确设置为派生类型,那么为什么它为基类型和派生类型都创建了节点级别呢?如何防止它这样做?

【问题讨论】:

    标签: c# .net xml-serialization


    【解决方案1】:

    我认为你的问题在于这一行:

    [XmlArrayItem("Exercise", Type = typeof (ExerciseXmlSerializer<Exercise>))]
    

    我不认为您要表明项目的类型是序列化程序的类型。如果要实现 IXmlSerializable,则需要在要序列化的类上。

    这是我要工作的内容:

    public class Keyboarding
    {
        [XmlArray("Exercises")]
        [XmlArrayItem("Exercise")]
        public Collection<Exercise> UnprocessedExercises { get; set; }
    
        public Keyboarding()
        {
            UnprocessedExercises = new Collection<Exercise>();
            UnprocessedExercises.Add(new StandardExercise());
        }
    }
    
    [XmlInclude(typeof(StandardExercise))]
    public class Exercise
    {
    }
    [Serializable]
    public class StandardExercise : Exercise
    {
    }
    

    这会产生类似于以下的输出:

    <?xml version=\"1.0\"?>
    <Keyboarding xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
      <Exercises>
        <Exercise xsi:type=\"StandardExercise\" />
      </Exercises>
    </Keyboarding>
    

    如果您不希望在输出中包含xsi:type,可以使用this question 的答案。

    【讨论】:

    • 当我尝试反序列化具有相同 xml 格式的初始数据时,格式会中断。当我修改代码和初始 xml 以匹配您的代码时,它在反序列化时将所有内容都键入为基本类型并丢失了所有子类化。我将项目的类型指定为 xml 序列化程序是因为几乎有 2 打可能的派生类可以键入它们,并且 xml 中的项目和顺序未知。这让我可以使用 Type 属性并在我的自定义序列化程序中使用反射来构建派生对象。我将编辑我的问题以澄清一下。
    • @HotN:您是否尝试过将自定义序列化代码直接实现到练习类?当我尝试按原样运行代码时出现异常,正是 XmlArrayItem 中的 typeof (ExerciseXmlSerializer&lt;Exercise&gt;) 导致了问题。您也可以尝试编写自定义 xmlwriter,如我的答案末尾链接的问题的答案所示。
    • 问题肯定是由typeof(ExerciseXmlSerializer&lt;Exercise&gt;) 部分引起的,但我发现将其更改为仅练习会解决序列化问题,但会破坏我的反序列化,因为派生类类型由属性确定.正如您所建议的,我最终通过将原始代码保留在练习集合中但实现了我自己的 XmlTextWriter 来使其工作。这感觉像是一种复杂的解决方案,但我确实喜欢它不需要我列出 20 个派生类作为 [XmlInclude]。总之,结果就是结果。谢谢!
    【解决方案2】:

    您应该能够使用XmlAttributeOverrides 来完成您的要求。在这种情况下,你可能会做这样的事情。示例代码有点粗糙,因为您没有包含整个对象图,但希望这会为您指明正确的方向。

    List<Type> extraTypes = new List<Type>();
    XmlAttributes attrs = new XmlAttributes();
    
    extraTypes.Add(typeof(Exercise));
    extraTypes.Add(typeof(StandardExercise));
    
    XmlElementAttribute attr = new XmlElementAttribute
    {
        ElementName = "Exercise",
        Type = typeof(Exercise)
    };
    attrs.XmlElements.Add(attr);
    
    attr = new XmlElementAttribute
    {
        ElementName = "StandardExercise",
        Type = typeof(StandardExercise)
    };
    attrs.XmlElements.Add(attr);
    
    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    overrides.Add(typeof(Keyboarding), "Keboarding", attrs);
    
    return new XmlSerializer(typeof(Keyboarding), overrides, extraTypes.ToArray(),
        new XmlRootAttribute("Keyboarding"), string.Empty);
    

    这应该允许您创建一个看起来像这样的 XML 树。这不是您要查找的内容,但具有描述性。

    <Keyboarding xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <Exercises>
            <StandardExercise Id="3" ActivityNumber="5" SubActivityNumber="b">
                <Title>Test Title</Title>
                <Instructions>Downloaded Update Instructions</Instructions>
            </StandardExercise >
        </Exercises>
    </Keyboarding>
    

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多