2012-11-24 5 views
9

값을 serialize하는 경우 : 데이터에 값이없는 경우 형식이 아래와 같습니다.데이터가없는 경우 XmlSerializer에서 자체 닫기 태그를 방지하십시오.

<Note> 
     <Type>Acknowledged by PPS</Type> 
     <Data /> 
    </Note> 

하지만 제가 아래 형식의 XML 데이터를 원하는 : 내가 쓴이 들어

<Note> 
     <Type>Acknowledged by PPS</Type> 
     <Data></Data> 
    </Note> 

코드 :

[Serializable] 
public class Notes 
{ 
    [XmlElement("Type")] 
    public string typeName { get; set; } 

    [XmlElement("Data")] 
    public string dataValue { get; set; } 
} 

내가 무엇을 알아낼 수 아니다 데이터가 아무 값도 지정하지 않으면 아래 형식의 데이터를 얻습니다.

<Note> 
     <Type>Acknowledged by PPS</Type> 
     <Data></Data> 
    </Note> 
+0

왜 이렇게하고 싶은지 잘 모르겠지만 작성한 xml은 실제로 유효하지 않습니다. 당신은 결코 데이터 요소를 닫지 않습니다. –

+0

나는이 다음 [XmlElementAttribute (거짓 ISNULLABLE =)] 완전히 의 차이는 실제로 작은 문제, 일반적으로 직접 불완전/버그 구현에 묶여 때 내가 –

+5

시간을 원하지 않는 무시를 사용하는 경우. 왜 이걸 원하니? –

답변

1

IMO Serialization을 사용하여 원하는 XML을 생성 할 수 없습니다.

XDocument xDocument = new XDocument(); 
XElement rootNode = new XElement(typeof(Notes).Name); 
foreach (var property in typeof(Notes).GetProperties()) 
{ 
    if (property.GetValue(a, null) == null) 
    { 
     property.SetValue(a, string.Empty, null); 
    } 
    XElement childNode = new XElement(property.Name, property.GetValue(a, null)); 
    rootNode.Add(childNode); 
} 
xDocument.Add(rootNode); 
XmlWriterSettings xws = new XmlWriterSettings() { Indent=true }; 
using (XmlWriter writer = XmlWriter.Create("D:\\Sample.xml", xws)) 
{ 
    xDocument.Save(writer); 
} 

홈페이지 캐치 in case your value is null, you should set it to empty string -하지만,이 같은 원하는 스키마를 생성하는 LINQ to XML를 사용할 수 있습니다. 그것은 force the closing tag to be generated 일 것입니다. 값이 null 인 경우 닫는 태그가 만들어지지 않습니다.

9

사용자 고유의 XmlTextWriter를 만들어 직렬화 프로세스로 전달하면됩니다.

public class MyXmlTextWriter : XmlTextWriter 
{ 
    public MyXmlTextWriter(Stream stream) : base(stream, Encoding.UTF8) 
    { 

    } 

    public override void WriteEndElement() 
    { 
     base.WriteFullEndElement(); 
    } 
} 

다음을 사용하여 결과를 테스트 할 수 있습니다

class Program 
{ 
    static void Main(string[] args) 
    { 
     using (var stream = new MemoryStream()) 
     { 
      var serializer = new XmlSerializer(typeof(Notes)); 
      var writer = new MyXmlTextWriter(stream); 
      serializer.Serialize(writer, new Notes() { typeName = "Acknowledged by PPS", dataValue="" }); 
      var result = Encoding.UTF8.GetString(stream.ToArray()); 
      Console.WriteLine(result); 
     } 
     Console.ReadKey(); 
    } 
+0

주의 : serialize/deserialized 할 때'null -> ""이됩니다. –

+1

작동하지만 각 요소 다음에 줄 바꿈없이 XML이 생성됩니다. ( – SuperJMN

+1

@SuperJMN'XmlWriter'를 둘러 쌀 필요가 있습니다. 기본 XmlWriter에는'Indent'가'true'로 설정된'XmlWriterSettings'가 필요하고' NewLineChars'가 의미있는 것으로 설정되었습니다. 예 : http://pastebin.com/G2bZNQnQ ('TextWriter' 대신'Stream'과 함께 작동합니다.) – domi1819

0

Kludge 시간 - XML의 문서가 각 노드를 통해 이동 생성 된 기본적 후 Generate System.Xml.XmlDocument.OuterXml() output thats valid in HTML

를 참조 자녀가없는 경우 빈 텍스트 노드를 추가

// Call with 
addSpaceToEmptyNodes(xmlDoc.FirstChild); 

private void addSpaceToEmptyNodes(XmlNode node) 
{ 
    if (node.HasChildNodes) 
    { 
     foreach (XmlNode child in node.ChildNodes) 
      addSpaceToEmptyNodes(child); 
    } 
    else   
     node.AppendChild(node.OwnerDocument.CreateTextNode("")) 
} 

(예. 이 작업을 수행해야합니다.하지만 XML을 다른 시스템에 보내면 쉽게 해결할 수 없으므로 실용적이어야합니다.

+0

if (노드 .HasChildNodes)'to (node.HasChildNodes && node.NodeType! = XmlNodeType.Text) ' – BurnsBA

1

자체 필드가 ​​추가되지 않도록 자체 필드를 추가 할 수 있습니다 요소.

[XmlText] 
public string datavalue= " "; 

또는 클래스의 코드를 원한다면 클래스는 다음과 같아야합니다.

public class Notes 
{ 
    [XmlElement("Type")] 
    public string typeName { get; set; } 

    [XmlElement("Data")] 
    private string _dataValue; 
    public string dataValue { 
     get { 
      if(string.IsNullOrEmpty(_dataValue)) 
      return " "; 
      else 
      return _dataValue; 
     } 
     set { 
      _dataValue = value; 
     } 
    } 
} 
+0

""여전히 값입니다. – Tommix

관련 문제