2014-04-09 3 views
1
public class MyStuff { 
    public string Name { get; set; } 

    public List<Annotation> Annotations { get; set; } 
} 

public class Annotation { 
    public string Name { get; set; } 
    public string Value { get; set; } 
} 

일련의 주석을 일련의 XML 속성으로 직렬화하는 방법은 무엇입니까?속성으로 이름/값 쌍을 직렬화하는 방법

+0

xml이 직렬화 후 어떻게 보일지에 대한 정보를 제공해주십시오. – MUG4N

+0

내 마지막 질문에 대한 마지막 줄. –

답변

0

IXmlSerializable 인터페이스는 모든 클래스의 직렬화를 사용자 정의 할 수 있습니다.

0
XmlDocument doc = new XmlDocument(); // Creating an xml document 
XmlElement root =doc.CreateElement("rootelement"); doc.AppendChild(root); // Creating and appending the root element 
XmlElement annotation = doc.CreateElement("Name"); 
XmlElement value = doc.CreateElement("Value"); 
annotation.InnerText = "Annotation Name Here"; 
value.InnerText = "Value Here"; 
doc.AppendChild(annotation); 
doc.AppendChild(value); 

var x = new MyStuff { 
    Name = "Stuff", 
    Annotations = new [] { 
     new Annotation { Name = "Note1", Value = "blah" }, 
     new Annotation { Name = "Note2", Value = "blahblah" } 
    }.ToList() 
}; 

// turns into something like: 
<MyStuff Name="Stuff" ann:Note1="blah" ann:Note2="blahblah" /> 
당신은 모든 목록을 좁히고 루프에서 같은 일을 할 수 있습니다.

0

이 속성에 속성 [XmlAttribute]를 추가 할 수있는 일이다

public class Annotation 
{ 
    [XmlAttribute] 
    public string Name { get; set; } 

    [XmlAttribute] 
    public string Value { get; set; } 
} 

을 그리고 결과는 다음과 같이 될 것입니다 : ann는 XML 네임 스페이스에만 유효한 경우

<Annotations> 
    <Annotation Name="Note1" Value="blah" /> 
    <Annotation Name="Note2" Value="blahblah" /> 
</Annotations> 
1

ann:Note1이며,

XNamespace ns = "Annotation"; 

XElement xElem = new XElement("MyStuff", new XAttribute("Name",x.Name)); 
xElem.Add(x.Annotations 
      .Select(a => new XAttribute(ns + a.Name, a.Value))); 

var xml = xElem.ToString(); 

OUTPUT :

<MyStuff Name="Stuff" p1:Note1="blah" p1:Note2="blahblah" xmlns:p1="Annotation" /> 
+0

그게 내가 원하는 올바른 출력이지만 직렬화를 사용하고 싶습니다. 이것은 대형 객체 계층 구조의 일부이며 전체 내용을 다시 쓰지 않는 것을 선호합니다. –

+0

@ harley.333 가능한 경우 XML 직렬화가 너무 까다로울 수 있습니다. 먼저 객체를 다른 객체로 변환 한 다음 직렬화를 수행해야합니다 (위의 코드와 크게 다르지는 않음) – EZI