当没有数据时,防止XmlSerializer中的自闭标签

Nis*_*mar 12 .net c# xml

当我序列化值时:如果数据中没有值,那么它就像下面的格式一样.

  <Note>
        <Type>Acknowledged by PPS</Type>
        <Data />
  </Note>
Run Code Online (Sandbox Code Playgroud)

但我想要的xml数据格式如下:

  <Note>
        <Type>Acknowledged by PPS</Type>
        <Data></Data>
  </Note>
Run Code Online (Sandbox Code Playgroud)

代码为此我写了:

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

    [XmlElement("Data")]
    public string dataValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如果数据没有分配任何值,我无法弄清楚如何以下面的格式实现数据.

  <Note>
        <Type>Acknowledged by PPS</Type>
        <Data></Data>
  </Note>
Run Code Online (Sandbox Code Playgroud)

arm*_*oon 11

您可以通过创建自己的XmlTextWriter来传递到序列化过程.

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

    }

    public override void WriteEndElement()
    {
        base.WriteFullEndElement();
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用以下方法测试结果:

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();
    }
Run Code Online (Sandbox Code Playgroud)


Roh*_*ats 1

IMO 不可能使用Serialization. 但是,您可以用来LINQ to 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);
}
Run Code Online (Sandbox Code Playgroud)

主要收获是in case your value is null, you should set it to empty string。它会force the closing tag to be generated。如果值为空,则不会创建结束标记。