C#에서 엔터티 클래스 및 XML을 변환하기 위한 샘플 코드에 대한 자세한 설명

黄舟
풀어 주다: 2017-03-16 11:47:26
원래의
1788명이 탐색했습니다.

이 글은 C#XML 간의 변환에 대한 정보를 주로 소개하고 있으니 관심 있는 분들은 참고하시기 바랍니다. 🎜>1. 엔터티 클래스를 XML로 변환

엔터티 클래스를 XML로 변환하려면 XmlSerializer 클래스의 Serialize 메서드를 사용하여 엔터티 클래스를 직렬화해야 합니다

public static string XmlSerialize<T>(T obj)
{
  using (StringWriter sw = new StringWriter())
  {
    Type t= obj.GetType();    
    XmlSerializer serializer = new XmlSerializer(obj.GetType());
    serializer.Serialize(sw, obj);
    sw.Close();
    return sw.ToString();
  }
}
로그인 후 복사

예:

1. 엔터티 클래스 정의

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
 [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
 public class Request
 {

  public string System { get; set; }
  public string SecurityCode { get; set; }
  public PatientBasicInfo PatientInfo { get; set; }  
 }

 /// <remarks/>
 [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
 public partial class PatientBasicInfo
 {
  public string PatientNo { get; set; }
  public string PatientName { get; set; }
  public string Phoneticize { get; set; }
  public string Sex { get; set; }
  public string Birth { get; set; }
  public string BirthPlace { get; set; }
  public string Country { get; set; }
  public string Nation { get; set; }
  public string IDNumber { get; set; }
  public string SecurityNo { get; set; }
  public string Workunits { get; set; }
  public string Address { get; set; }
  public string ZIPCode { get; set; }
  public string Phone { get; set; }
  public string ContactPerson { get; set; }
  public string ContactShip { get; set; }
  public string ContactPersonAdd { get; set; }
  public string ContactPersonPhone { get; set; }
  public string OperationCode { get; set; }
  public string OperationName { get; set; }
  public string OperationTime { get; set; }
  public string CardNo { get; set; }
  public string ChangeType { get; set; }

 }
로그인 후 복사


2. 엔터티 클래스에 값을 할당하고 엔터티 클래스를

직렬화를 통해 XML 형식의 문자열로

Request patientIn = new Request();
   patientIn.System = "HIS";
   patientIn.SecurityCode = "HIS5";

   PatientBasicInfo basicInfo = new PatientBasicInfo();
   basicInfo.PatientNo = "1234";
   basicInfo.PatientName = "测试";
   basicInfo.Phoneticize = "";
   basicInfo.Sex = "1";
   basicInfo.Birth = "";
   basicInfo.BirthPlace = "";
   basicInfo.Country = "";
   basicInfo.Nation = "";
   basicInfo.IDNumber = "";
   basicInfo.SecurityNo = "";
   basicInfo.Workunits = "";
   basicInfo.Address = "";
   basicInfo.ZIPCode = "";
   basicInfo.Phone = "";
   basicInfo.ContactShip = "";
   basicInfo.ContactPersonPhone = "";
   basicInfo.ContactPersonAdd = "";
   basicInfo.ContactPerson = "";
   basicInfo.ChangeType = "";
   basicInfo.CardNo = "";
   basicInfo.OperationCode = "";
   basicInfo.OperationName = "";
   basicInfo.OperationTime = "";

   patientIn.PatientInfo = basicInfo;

   //序列化
   string strxml = XmlSerializeHelper.XmlSerialize<Request>(patientIn);
로그인 후 복사


3. 생성된 XML 인스턴스

<?xml version="1.0" encoding="utf-16"?>
<Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <System>HIS</System>
 <SecurityCode>HIS5</SecurityCode>
 <PatientInfo>
 <PatientNo>1234</PatientNo>
 <PatientName>测试</PatientName>
 <Phoneticize />
 <Sex>1</Sex>
 <Birth />
 <BirthPlace />
 <Country />
 <Nation />
 <IDNumber />
 <SecurityNo />
 <Workunits />
 <Address />
 <ZIPCode />
 <Phone />
 <ContactPerson />
 <ContactShip />
 <ContactPersonAdd />
 <ContactPersonPhone />
 <OperationCode />
 <OperationName />
 <OperationTime />
 <CardNo />
 <ChangeType />
 </PatientInfo>
</Request>
로그인 후 복사


2. XML을 엔터티 클래스로 변환합니다.

은 XML을 해당 엔터티 클래스로 변환합니다. XML을 역직렬화하려면 XmlSerializer 클래스의 Deserialize 메서드를 사용해야 합니다.

public static T DESerializer<T>(string strXML) where T:class
{
  try
 {
   using (StringReader sr = new StringReader(strXML))
   {
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    return serializer.Deserialize(sr) as T;
   }
  }
  catch (Exception ex)
  {
   return null;
  }
}
로그인 후 복사

예:


위 예의 직렬화된 XML을 엔터티 클래스로 역직렬화

//反序列化
Request r = XmlSerializeHelper.DESerializer<Request>(strxml);
로그인 후 복사

위 내용은 C#에서 엔터티 클래스 및 XML을 변환하기 위한 샘플 코드에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!