2010-11-20 5 views

답변

28

여기에 더 적은 설명이 있지만 좋은 출발점이라고 생각합니다.

XmlRootAttribute - 직렬화되는 객체 그래프의 루트 요소가 될 클래스에 대한 스키마 정보를 제공하는 데 사용됩니다. 이것은 클래스, 구조체, 열거 형, 반환 값의 인터페이스에만 적용 할 수 있습니다.

XmlElementAttribute - 하위 요소로 직렬화되는 방식을 제어하는 ​​클래스의 속성에 대한 스키마 정보를 제공합니다. 이 속성은 필드 (클래스 변수 멤버), 속성, 매개 변수 및 반환 값에만 적용 할 수 있습니다.

첫 번째 두 XmlRootAttributeXmlElementAttribute은 XmlSerializer와 관련됩니다. 그 다음은 런타임 형식 지정자에서 사용하며 XmlSerialization을 사용할 때는 적용되지 않습니다.

SerializableAtttrible - 형식이 SoapFormatter 또는 BinaryFormatter와 같은 런타임 형식 지정자로 serialize 될 수 있음을 나타내는 데 사용됩니다. 형식 자 중 하나를 사용하여 형식을 serialize해야하며 위임자, 열거 형, 구조체 및 클래스에 적용 할 수있는 경우에만 필요합니다.

위의 설명에 도움이되는 간단한 예가 있습니다.

// This is the root of the address book data graph 
// but we want root written out using camel casing 
// so we use XmlRoot to instruct the XmlSerializer 
// to use the name 'addressBook' when reading/writing 
// the XML data 
[XmlRoot("addressBook")] 
public class AddressBook 
{ 
    // In this case a contact will represent the owner 
    // of the address book. So we deciced to instruct 
    // the serializer to write the contact details out 
    // as <owner> 
    [XmlElement("owner")] 
    public Contact Owner; 

    // Here we apply XmlElement to an array which will 
    // instruct the XmlSerializer to read/write the array 
    // items as direct child elements of the addressBook 
    // element. Each element will be in the form of 
    // <contact ... /> 
    [XmlElement("contact")] 
    public Contact[] Contacts; 
} 

public class Contact 
{ 
    // Here we instruct the serializer to treat FirstName 
    // as an xml element attribute rather than an element. 
    // We also provide an alternate name for the attribute. 
    [XmlAttribute("firstName")] 
    public string FirstName; 

    [XmlAttribute("lastName")] 
    public string LastName; 

    [XmlElement("tel1")] 
    public string PhoneNumber; 

    [XmlElement("email")] 
    public string EmailAddress; 
} 

<addressBook> 
    <owner firstName="Chris" lastName="Taylor"> 
    <tel1>555-321343</tel1> 
    <email>[email protected]</email> 
    </owner> 
    <contact firstName="Natasha" lastName="Taylor"> 
    <tel1>555-321343</tel1> 
    <email>[email protected]</email> 
    </contact> 
    <contact firstName="Gideon" lastName="Becking"> 
    <tel1>555-123423</tel1> 
    <email>[email protected]</email> 
    </contact> 
</addressBook> 
+0

당신이 우리가 태그 이있는 XML에 대한 Attribiutes을 추가하는 방법을 알 수있는 다음과 같은 형식의 XML을 줄 것 인 XmlSerializer를 직렬화 주소록의 인스턴스 위를 감안할 때 모든 연락처, 주소록 태그 안에? – Dhanashree

+2

@Dhanashree, 연락처 요소를 부모 연락처 요소로 감쌀 것을 요청하고 있습니까? 그렇다면 'Contact [] contacts'에서 [XmlElement ("contact")]을 제거 할 수 있습니다. 이름을 제어하려면 [XmlArray ("contacts")], XmlArrayItem (" 연락처 ")] 루트 및 컬렉션의 항목 이름을 제어합니다. –

+0

감사! 그게 도움이 :) – Dhanashree