Десериализовать простой объект массива XML в C # для службы WCF - PullRequest
0 голосов
/ 21 октября 2019

В течение 3 дней я сталкиваюсь с той же проблемой, и я не могу понять, что я делаю неправильно.

Контекст: я создаю новую службу WCF для фиксированного XML.

Проблема: похоже, десериализация XML идет неправильно. Я получаю data объект обратно, но без свойства items заполнено.

До сих пор пробовали:

  • Создание класса C # с xsd 4.0 (в настоящее время используется в проекте WCF) и 4.7.
  • Добавление нескольких атрибутов, таких как:

    [ServiceContract(Namespace = "urn:oasis:names:tc:SPML:2:0"), XmlSerializerFormat].
    [System.Xml.Serialization.XmlArrayItemAttribute("attr", IsNullable = false)] 
    

    в Items свойство

Это XML, который я собираюсь получить:

<spml:data xmlns:spml="urn:oasis:names:tc:SPML:2:0">
    <attr name="mailone" xmlns="urn:oasis:names:tc:DSML:2:0:core">
        <value>xxxx@gmail.com</value>
    </attr>
    <attr name="mailtwo" xmlns="urn:oasis:names:tc:DSML:2:0:core">
        <value>xxxx@gmail.com</value>
    </attr>
    <attr name="mailthree" xmlns="urn:oasis:names:tc:DSML:2:0:core">
        <value>xxxx@gmail.com</value>
    </attr>
</spml:data>

С xsd(4.0 в настоящее время используется в проекте wcf для других объектов) Я получаю этот класс c # из xsd:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.33440.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "urn:oasis:names:tc:SPML:2:0")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:oasis:names:tc:SPML:2:0", IsNullable = false)]
public partial class data
{
    private attr[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("attr")]
    public attr[] Items
    {
        get
        {
            return this.itemsField;
        }
        set
        {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "urn:oasis:names:tc:SPML:2:0")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:oasis:names:tc:SPML:2:0", IsNullable = false)]
public partial class attr
{

    private string valueField;

    private string nameField;

    /// <remarks/>
    public string value
    {
        get
        {
            return this.valueField;
        }
        set
        {
            this.valueField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }
}

Я написал эту программу, чтобы упростить проблему отображения:

using System;
using System.Xml;
using System.Xml.Serialization;

namespace XmlDeserializer
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer ser = new XmlSerializer(typeof(data));
            data data;

            using (XmlReader reader = XmlReader.Create(PATH))
            {
                data = (data)ser.Deserialize(reader);
            }
        }
    }
}

Есливы запускаете это консольное приложение с классом C # в том же проекте и отлаживаете данные, вы возвращаете объект данных с items = null.

Может кто-то направил меня в правильном направлении?

РЕДАКТИРОВАТЬ: это связано с пространствами имен: я удалил все пространства имен в объектах XML и c #, и это сработало.

С уважением, Питер

1 Ответ

1 голос
/ 21 октября 2019

Следующий код работает. Я изменил пространства имен:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication137
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            XmlSerializer serializer = new XmlSerializer(typeof(data));
            data d = (data)serializer.Deserialize(reader);
        }

    }
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:oasis:names:tc:SPML:2:0", IsNullable = false)]
    public partial class data
    {
        private attr[] itemsField;

        /// <remarks/>
        [XmlElement(ElementName = "attr", Namespace = "urn:oasis:names:tc:DSML:2:0:core")]
        public attr[] Items
        {
            get
            {
                return this.itemsField;
            }
            set
            {
                this.itemsField = value;
            }
        }
    }

    [System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:oasis:names:tc:DSML:2:0:core", IsNullable = false)]
    public partial class attr
    {

        private string valueField;

        private string nameField;

        /// <remarks/>
        public string value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }
    }

}
...