1

The Problem

I have an issue when I deserialize my xml, one of the child elements is not being deserialized. It is null in the class instance despite being populated in the xml.

A little Background

I used XsdObjectGenerator to create poco classes based on my .xsd. I was then able to deserialize the xml into a class instance and work with the objects.

I modifed the autogenerated classes by wrapping them in a namespace called 'TFS'.

At a certain point in the project, I found it necessary to place one of the child elements in it's own namespace called 'COM'.

The next time I attempted to deserialized the xml into a class instance, the child element is not being deserialized.

Here is the pertinent snippet of TFS class code with the child element namespace changed to COM. It also includes the parent element OrdDtl which remains in the TFS namespace.

[XmlRoot(ElementName="OrdDtl",Namespace=Declarations.SchemaVersion,IsNullable=false),Serializable]
    public class OrdDtl
    {
            [XmlElement(Type=typeof(COM.AcctSetup), ElementName="AcctSetup", IsNullable=false, Form=XmlSchemaForm.Qualified, Namespace = Declarations.SchemaVersion)]
        [EditorBrowsable(EditorBrowsableState.Advanced)]
            public COM.AcctSetup __AcctSetup;

        [XmlIgnore]
            public COM.AcctSetup AcctSetup
        {
            get
            {
                if (__AcctSetup == null) __AcctSetup = new COM.AcctSetup();     
                return __AcctSetup;
            }
            set {__AcctSetup = value;}
        }

Here is the AcctSetup declaration in the COM namespace which is contained in it's own file:

[XmlRoot(ElementName = "AcctSetup", Namespace = Declarations.SchemaVersion, IsNullable = false), Serializable]
    public class AcctSetup
    {
......
}

and here is my deserialize function:

public static T XMLStringToXMLObject<T>(string pXmlString)
    {
        T retVal = default(T);   

        try
        {
            XmlSerializer vSerializer = new XmlSerializer(typeof(T));
            MemoryStream vMemoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlString));
            XmlTextWriter vXmlTextWriter = new XmlTextWriter(vMemoryStream, Encoding.UTF8);
            retVal = (T)vSerializer.Deserialize(vMemoryStream);
        }
        catch (System.Exception ex)
        {
            if (ExceptionMain.LogException(ex))
                throw;
        }

        return retVal;
    }

Any assistance in getting the COM.AcctSetup element to deserialize is very much appreciated. Let me know if you need additional info or code samples.

4

1 回答 1

1

我想通了。我试图反序列化的 xml 文件在根元素中包含以下属性:

xmlns="tfs"

因此 xml 文件中的每个元素都在这个 xml 命名空间下。

我对代码的更改本质上是将 AcctSetup 元素放在单独的 xml 命名空间“com”下。因此,为了反序列化文件,文件需要根元素中的“xmlns="tfs"' 和 acctsetup 子属性上的单独的 'xmlns="com"' 属性。

由于这不是我在 AcctSetup 元素上方的父元素上收到的文件的格式,因此被反序列化为类实例。

我的解决方案是将“acctsetup”元素再次移回“tfs”命名空间。在我的特殊情况下,唯一的缺点是代码重复了一点点 - 但一切都恢复了。

于 2010-09-15T12:57:13.847 回答