C#—— XML的处理(string 和 xml 的相互转化)

葛昕
2023-12-01

一、实体类转为 XML字符串

		string requestXML = Serializer(typeof(CnoocSAPAccountPay.DT_Entrade_AccountPay_SAP_Request), req);//CnoocSAPAccountPay.DT_Entrade_AccountPay_SAP_Request为实体类类型,req为实体类对象

		private string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //Serialize object
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();

            return str;
        }

二、string 转 xml

string content = Serializer(req.GetType(), req);//序列化实体类
XmlDocument xdocC = new XmlDocument();
xdocC.LoadXml(content);//xdoC即为xml数据对象

XmlNodeList topMC = xdocC.SelectNodes("//DT_Entrade_AccountPay_SAP_Request");//查找对应结点 
foreach (XmlElement tm in topMC)
{
	content = tm.InnerXml.ToString();//获取结点内部xml数据
}

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(postResult);
XmlNodeList topR = xdoc.SelectNodes("//Return");//将所有结点名为Return的数据拿出来,形成List集合
XmlNodeList topI = xdoc.SelectNodes("//Item");//将所有结点名为Item的数据拿出来,形成List集合

foreach (XmlElement tm in topR) //congList结合中取出要的值
{
	result.RetCode = tm.GetElementsByTagName("RetCode")[0].InnerText;//取出RetCode结点的值
	result.RetMsg = tm.GetElementsByTagName("RetMsg")[0].InnerText;//取出RetMsg结点的值
}
 类似资料: