【发布时间】:2020-02-10 18:31:07
【问题描述】:
我已将一个 XML 文件反序列化为一个类,该类使我的肥皂请求对象。 当我序列化 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 文件将被该标记为空。
有什么方法可以进行迭代并做出我需要的东西?
这是一个sn-p代码,其中开始信封
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; }
}
然后继续处理包含其他类的主体
[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; }
}
【问题讨论】:
-
Envelope是自定义类吗?还是来自某些第三方库?如果这些类是自定义的,您应该将它们添加到您的问题中 -
没有信封是我的 xml 的根元素,它包含另一个..
-
你有没有尝试在构造函数上初始化这些子类?
-
是的,我可以,但我正在寻找解决方案,因为我有很多文件和很多类,它们的属性嵌套在列表或其他类型的对象中。
标签: c# xml xml-serialization