Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实例化从xml序列化的所有类对象_C#_Xml_Xml Serialization - Fatal编程技术网

C# 实例化从xml序列化的所有类对象

C# 实例化从xml序列化的所有类对象,c#,xml,xml-serialization,C#,Xml,Xml Serialization,我已经将一个XML文件反序列化到一个类中,该类构成了我的soap请求对象。 当我序列化C#类时,大多数类对象不会填充输出xml文件 范例 GetUserReq.Envelope getUser = new GetUserReq.Envelope(); getUserResponse = new GetUserRes.Envelope(); getUser.Body = new GetUserReq.Body(); getUser.Body.GetUser = new GetUserReq.Get

我已经将一个XML文件反序列化到一个类中,该类构成了我的soap请求对象。 当我序列化C#类时,大多数类对象不会填充输出xml文件

范例

GetUserReq.Envelope getUser = new GetUserReq.Envelope();
getUserResponse = new GetUserRes.Envelope();
getUser.Body = new GetUserReq.Body();
getUser.Body.GetUser = new GetUserReq.GetUser();
getUser.Body.GetUser.ReturnedTags = new GetUserReq.ReturnedTags();

if (allReturnTags)
{
    getUser.Body.GetUser.ReturnedTags.AssociatedGroups = new GetUserReq.AssociatedGroups();
    getUser.Body.GetUser.ReturnedTags.AssociatedDevices = new GetUserReq.AssociatedDevices();
    getUser.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup = new GetUserReq.UserGroup() { Name = "", UserRoles = new GetUserReq.UserRoles() };
    getUser.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup.UserRoles = new GetUserReq.UserRoles() { UserRole = "" };
}
对于嵌套在“信封”中的每个项目,我需要创建新对象,否则输出xml文件将被该标记清空

有没有什么方法可以做一次迭代并得到我所需要的

这是一段代码,其中开始使用信封

public class GetUserReq {
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public class Envelope
        {
            [XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
            public string Header { get; set; }
            [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
            public Body Body { get; set; }
            [XmlAttribute(AttributeName = "soapenv", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Soapenv { get; set; }
            [XmlAttribute(AttributeName = "ns", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Ns { get; set; }
        }
继续讨论包含其他类的body

[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Body
    {
        [XmlElement(ElementName = "getUser", Namespace = "http://www.cisco.com/AXL/API/9.1")]
        public GetUser GetUser { get; set; }
    }

您只定义了类,没有类的属性。见下面的代码:

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            GetUserReq userReq = new GetUserReq();
            userReq.Envelope = new Envelope();
            GetUserResponse userResponse = new GetUserResponse();
            userResponse.Envelope = new Envelope();
            userReq.Body = new Body();
            userReq.Body.GetUser = new GetUser();
            userReq.Body.GetUser.ReturnedTags = new ReturnedTags();

            Boolean allReturnTags = true;
            if (allReturnTags)
            {
                userReq.Body.GetUser.ReturnedTags.AssociatedGroups = new AssociatedGroups();
                userReq.Body.GetUser.ReturnedTags.AssociatedDevices = new AssociatedDevices();
                userReq.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup = new UserGroup() { Name = "", UserRoles = new UserRoles() };
                userReq.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup.UserRoles = new UserRoles() { UserRole = "" };
            }

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME, settings);

            XmlSerializer serializer = new XmlSerializer(typeof(GetUserReq));
            serializer.Serialize(writer, userReq);
        }
    }
    [XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Body
    {
        [XmlElement(ElementName = "getUser", Namespace = "http://www.cisco.com/AXL/API/9.1")]
        public GetUser GetUser { get; set; }
    }
    public class GetUser
    {
        public ReturnedTags ReturnedTags { get; set; }
    }
    public class ReturnedTags
    {
        public AssociatedGroups AssociatedGroups { get; set; }
        public AssociatedDevices AssociatedDevices { get; set; }
    }
    public class GetUserReq
    {
        public Envelope Envelope { get; set; }
        public Body Body { get; set; }

    }
    public class GetUserResponse
    {
        public Envelope Envelope { get; set; }

    }
    [XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Envelope
    {
        [XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public string Header { get; set; }
        [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public Body Body { get; set; }
        [XmlAttribute(AttributeName = "soapenv", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Soapenv { get; set; }
        [XmlAttribute(AttributeName = "ns", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Ns { get; set; }
    }
    public class AssociatedGroups
    {
        public UserGroup UserGroup { get; set; }
    }
    public class AssociatedDevices
    {
    }
    public class UserGroup
    {
        public UserRoles UserRoles { get; set; }
        public string Name { get; set; }
    }
    public class UserRoles
    {
        public string UserRole { get; set; }
    }
}

您只定义了类,没有类的属性。见下面的代码:

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            GetUserReq userReq = new GetUserReq();
            userReq.Envelope = new Envelope();
            GetUserResponse userResponse = new GetUserResponse();
            userResponse.Envelope = new Envelope();
            userReq.Body = new Body();
            userReq.Body.GetUser = new GetUser();
            userReq.Body.GetUser.ReturnedTags = new ReturnedTags();

            Boolean allReturnTags = true;
            if (allReturnTags)
            {
                userReq.Body.GetUser.ReturnedTags.AssociatedGroups = new AssociatedGroups();
                userReq.Body.GetUser.ReturnedTags.AssociatedDevices = new AssociatedDevices();
                userReq.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup = new UserGroup() { Name = "", UserRoles = new UserRoles() };
                userReq.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup.UserRoles = new UserRoles() { UserRole = "" };
            }

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME, settings);

            XmlSerializer serializer = new XmlSerializer(typeof(GetUserReq));
            serializer.Serialize(writer, userReq);
        }
    }
    [XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Body
    {
        [XmlElement(ElementName = "getUser", Namespace = "http://www.cisco.com/AXL/API/9.1")]
        public GetUser GetUser { get; set; }
    }
    public class GetUser
    {
        public ReturnedTags ReturnedTags { get; set; }
    }
    public class ReturnedTags
    {
        public AssociatedGroups AssociatedGroups { get; set; }
        public AssociatedDevices AssociatedDevices { get; set; }
    }
    public class GetUserReq
    {
        public Envelope Envelope { get; set; }
        public Body Body { get; set; }

    }
    public class GetUserResponse
    {
        public Envelope Envelope { get; set; }

    }
    [XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Envelope
    {
        [XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public string Header { get; set; }
        [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public Body Body { get; set; }
        [XmlAttribute(AttributeName = "soapenv", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Soapenv { get; set; }
        [XmlAttribute(AttributeName = "ns", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Ns { get; set; }
    }
    public class AssociatedGroups
    {
        public UserGroup UserGroup { get; set; }
    }
    public class AssociatedDevices
    {
    }
    public class UserGroup
    {
        public UserRoles UserRoles { get; set; }
        public string Name { get; set; }
    }
    public class UserRoles
    {
        public string UserRole { get; set; }
    }
}

你可以使用反射


公共对象级联初始值设定项(类型)
{
var newObj=Activator.CreateInstance(type);//创建目标类的新实例
Func query=q
=>q.PropertyType.IsClass&&//检查属性是否为类
q、 可以写入&&//检查属性是否不是只读的
q、 PropertyType!=typeof(string);//检查属性是否不是string
foreach(type.GetProperties().Where(查询)中的var el)
{
//创建el cascade的新实例
变量elistance=级联初始值设定项(el.PropertyType);
el.SetValue(新OBJ,Elistance);
}
返回newObj;
}
//一个通用重载,以便于使用
公共T级联初始值设定项()=>(T)级联初始值设定项(类型(T));
用法

var x=cascade初始值设定项();

此外,如果要控制哪些类应自动初始化,可以向类中添加一个空接口
interface IInitializable
,这样就可以在
Func查询中检查
IInitializable
类型的属性

e、 g

Func query=q
=>q.PropertyType.IsClass&&//检查属性是否为类
q、 可以写入&&//检查属性是否不是只读的
q、 属性类型!=typeof(string)&&//检查属性是否不是string
q、 PropertyType.GetInterfaces()//检查应该初始化哪些类
.Any(i=>i.Name==nameof(可初始化));
...
公共接口可初始化{}
公共类信封:可初始化{
.....
在dotnetfiddle上测试:


你可以使用反射


公共对象级联初始值设定项(类型)
{
var newObj=Activator.CreateInstance(type);//创建目标类的新实例
Func query=q
=>q.PropertyType.IsClass&&//检查属性是否为类
q、 可以写入&&//检查属性是否不是只读的
q、 PropertyType!=typeof(string);//检查属性是否不是string
foreach(type.GetProperties().Where(查询)中的var el)
{
//创建el cascade的新实例
变量elistance=级联初始值设定项(el.PropertyType);
el.SetValue(新OBJ,Elistance);
}
返回newObj;
}
//一个通用重载,以便于使用
公共T级联初始值设定项()=>(T)级联初始值设定项(类型(T));
用法

var x=cascade初始值设定项();

此外,如果要控制哪些类应自动初始化,可以向类中添加一个空接口
interface IInitializable
,这样就可以在
Func查询中检查
IInitializable
类型的属性

e、 g

Func query=q
=>q.PropertyType.IsClass&&//检查属性是否为类
q、 可以写入&&//检查属性是否不是只读的
q、 PropertyType!=typeof(string)&&&//检查属性是否不是string
q、 PropertyType.GetInterfaces()//检查应该初始化哪些类
.Any(i=>i.Name==nameof(可初始化));
...
公共接口可初始化{}
公共类信封:可初始化{
.....
在dotnetfiddle上测试:


我根据您的示例编写了这段代码,并根据我的需要进行了修改

    public T AllReturnTags<T>() => (T)AllReturnTags(typeof(T));

    public object AllReturnTags(Type type)
    {
        var newObj = Activator.CreateInstance(type); // create new instance of your target class

        Func<PropertyInfo, bool> query = q
             => q.PropertyType.IsClass &&         
                q.CanWrite;                  

        foreach (var el in type.GetProperties().Where(query))
        {
            // create new instance of el cascade
            if (el.PropertyType == typeof(string))
            {
                el.SetValue(newObj, "", null);
            }
            if (el.PropertyType == typeof(Int32))
            {
                el.SetValue(newObj, 0, null);
            }
            if (el.PropertyType.IsClass && el.PropertyType != typeof(string) && el.PropertyType != typeof(Int32) && el.PropertyType.IsGenericType == true && el.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
            {
                var elInstance = AllReturnTags(el.PropertyType);
                Type itemType = typeof(List<>).MakeGenericType(elInstance.GetType());
                IList res = (IList)Activator.CreateInstance(itemType);
                res.Add(elInstance);
                try { el.SetValue(newObj, res, null); } catch {  };
            }
            if (el.PropertyType.IsClass && el.PropertyType != typeof(string) && el.PropertyType != typeof(Int32) && el.PropertyType.IsGenericType != true )
            {
                var elInstance = AllReturnTags(el.PropertyType);
                try { el.SetValue(newObj, elInstance, null); } catch { return elInstance; };
            }

        }
        return newObj;
    }
public T AllReturnTags()=>(T)AllReturnTags(typeof(T));
公共对象AllReturnTags(类型)
{
var newObj=Activator.CreateInstance(type);//创建目标类的新实例
Func query=q
=>q.PropertyType.IsClass&&
q、 会写;
foreach(type.GetProperties().Where(查询)中的var el)
{
//创建el cascade的新实例
if(el.PropertyType==typeof(string))
{
el.SetValue(newObj,“”,null);
}
if(el.PropertyType==typeof(Int32))
{
el.SetValue(newObj,0,null);
}
如果(el.PropertyType.IsClass&&el.PropertyType!=typeof(string)&&el.PropertyType!=typeof(Int32)&&el.PropertyType.IsGenericType==true&&el.PropertyType.GetGenericTypeDefinition()=typeof(List))
{
var elistance=AllReturnTags(el.PropertyType);
Type itemType=typeof(List).MakeGenericType(elInstance.GetType());
IList res=(IList)Activator.CreateInstance(itemType);
res.Add(立场);
尝试{el.SetValue(newObj,res,null);}catch{};
}
if(el.PropertyType.IsClass&&el.PropertyType!=typeof(string)&&el.PropertyType!=typeof(Int32)&&el.PropertyType.IsGenericType!=true)
{
var elistance=AllReturnTags(el.PropertyType);
尝试{el.SetValue(newObj,elistance,null);}catch{return elistance;};
}
}
返回newObj;
}
这似乎适用于单个项目和列表。
Thx you@AliReza

我根据您的示例编写了这段代码,并对其进行了修改