当输入是数组或列表时,如何在c#中进行序列化
本文关键字:序列化 输入 数组 列表 | 更新日期: 2023-09-27 18:24:46
我正在使用Web服务发送电子邮件。我已经将xml发送到Web服务,它负责处理其余部分。
在newuseremail中,我将电子邮件列表转换为字符串,并将其传递给sendemail方法。
string newuseremail= string.Join(",", lstnewuseremail.ToArray());
所以这里的xml是
<emailRequest>
<toaddress>dasd@tg.com,adssd@tg.com</toaddress>
<subject>Welcome to ASF</subject>
<message />
<username>sda@tg.com</username>
</emailRequest>
但我希望xml是这种格式
<emailRequest>
<toaddress>dasd@tg.com</toaddress>
<toaddress>adssd@tg.com</toaddress>
<subject>Welcome to ASF</subject>
<message />
<username>sda@tg.com</username>
</emailRequest>
public string SendEmail(string newuseremail, string subject, string message, string myemail)
{
string url = "dskjshdkh";
emailRequest test = new emailRequest();
test.toaddress = newuseremail;
test.subject = subject;
test.message = message;
test.username = myemail;
//serialize the inputs
String XML;
XML = SerializeAnObject(test);
return HttpPost(XML, url);
}
//Serialize An Object
public static string SerializeAnObject(object AnObject)
{
XmlSerializer Xml_Serializer = new XmlSerializer(AnObject.GetType());
XmlSerializerNamespaces emptyNameSpace = new XmlSerializerNamespaces();
emptyNameSpace.Add("", "");
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
StringWriter stringWriter = new StringWriter();
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
Xml_Serializer.Serialize(xmlWriter, AnObject, emptyNameSpace);
}
return stringWriter.ToString();
}
}
更新:
我在这里分离阵列。但是xml是通过忽略所有的todress而形成的,在xml 中只使用最后一个todress
public string SendEmail(string newuseremail, string subject, string message, string myemail)
{
string url = "http://localhost:8080/SurelyKnownMediaService/services/service/sendemail/";
emailRequest test = new emailRequest();
string[] email = newuseremail.Split(',');
foreach (string word in email)
{
test.toaddress = Convert.ToString(word);
}
test.subject = subject;
test.message = message;
test.username = myemail;
//serialize the inputs
String XML;
XML = SerializeAnObject(test);
return HttpPost(XML, url);
}
我的建议是将List<string>
类型的另一个属性添加到正在序列化的类中,实现该属性的get
,该属性将解析文本toaddress
并填充列表,用XmlIgnore
属性标记现有的toaddress
,用[XmlElement("todress")]。
public class emailRequest
{
[XmlElement]
public List<string> toAddress { get; set; }
}