Prevent self closing tags in XmlSerializer when no data is present

后端 未结 5 938
孤街浪徒
孤街浪徒 2020-12-10 12:53

When I serialize the value : If there is no value present in for data then it\'s coming like below format.

  
        Acknowledged b         


        
相关标签:
5条回答
  • 2020-12-10 13:40

    You can do this by creating your own XmlTextWriter to pass into the serialization process.

    public class MyXmlTextWriter : XmlTextWriter
    {
        public MyXmlTextWriter(Stream stream) : base(stream, Encoding.UTF8)
        {
    
        }
    
        public override void WriteEndElement()
        {
            base.WriteFullEndElement();
        }
    }
    

    You can test the result using:

    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 讨论(0)
  • 2020-12-10 13:43

    IMO it's not possibe to generate your desired XML using Serialization. But, you can use LINQ to XML to generate the desired schema like this -

    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);
    }
    

    Main catch is in case your value is null, you should set it to empty string. It will force the closing tag to be generated. In case value is null closing tag is not created.

    0 讨论(0)
  • 2020-12-10 13:55

    In principal, armen.shimoon's answer worked for me. But if you want your XML output pretty printed without having to use XmlWriterSettings and an additional Stream object (as stated in the comments), you can simply set the Formatting in the constructor of your XmlTextWriter class.

    public MyXmlTextWriter(string filename) : base(filename, Encoding.UTF8)
    {
        this.Formatting = Formatting.Indented;
    }
    

    (Would have posted this as a comment but am not allowed yet ;-))

    0 讨论(0)
  • 2020-12-10 13:56

    Kludge time - see Generate System.Xml.XmlDocument.OuterXml() output thats valid in HTML

    Basically after XML doc has been generated go through each node, adding an empty text node if no children

    // 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(""))
    }
    

    (Yes I know you shouldn't have to do this - but if your sending the XML to some other system that you can't easily fix then have to be pragmatic about things)

    0 讨论(0)
  • 2020-12-10 13:57

    You can add a dummy field to prevent the self-closing element.

    [XmlText]
    public string datavalue= " ";
    

    Or if you want the code for your class then Your class should be like this.

    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 讨论(0)
提交回复
热议问题