【问题标题】:Serialize XmlAttribute which is an empty string [closed]序列化作为空字符串的 XmlAttribute [关闭]
【发布时间】:2020-02-06 15:50:47
【问题描述】:

我有一个代表足球运动员的类​​:

public class PlayerExtended
{
    [XmlAttribute("id")] public string Id { get; set; }
    [XmlAttribute("shortName")] public string ShortName { get; set; }
    [XmlAttribute("firstName")] public string FirstName { get; set; }
    [XmlAttribute("surName")] public string SurName { get; set; }
    [XmlAttribute("shirtNumber")] public string ShirtNumber { get; set; }
    [XmlAttribute("actions")] public string Actions { get; set; }
    [XmlAttribute("substitude")] public string Substitude { get; set; }
    [XmlAttribute("grade")] public string Grade { get; set; }
    [XmlAttribute("iconSmall")] public string IconSmall { get; set; }
    [XmlAttribute("position")] public string Position { get; set; }
    [XmlAttribute("squadPositionID")] public string SquadPositionId { get; set; }
    [XmlAttribute("squadPosition")] public string SquadPosition { get; set; }
    [XmlAttribute("inMinute")] public string InMinute { get; set; }
    [XmlAttribute("outMinute")] public string OutMinute { get; set; }
    [XmlAttribute("captain")] public string Captain { get; set; }
}

在为属性赋值后,其中一个玩家看起来像这样:

属性“Actions”是一个空字符串(NOT NULL)。

如果我序列化它,它看起来像这样:

<player id="51641" shortName="Bürki" firstName="Roman" surName="Bürki" shirtNumber="1" substitude="starter" grade="2,5" iconSmall="xxx.whatever.com" position="11" squadPositionID="1" squadPosition="Torwart"/>

但我希望它看起来像这样:

<player id="51641" shortName="Bürki" firstName="Roman" surName="Bürki" shirtNumber="1" actions="" substitude="starter" grade="2,5" iconSmall="xxx.whatever.com" position="11" squadPositionID="1" squadPosition="Torwart"/>

那么如何序列化一个空字符串的 XmlAttribute 呢?

【问题讨论】:

  • 您是否已经尝试使用 [System.Xml.Serialization.XmlElement(IsNullable = true)] 属性而不是 XmlAttribute ?成功了吗?
  • 是的,它“有效”......但它看起来像这样:
  • @ManojChoudhari XmlElement 与 XmlAttribute 不同,这不起作用
  • 无法复制。给定var player = new PlayerExtended { Id = "51641", Actions = "", };,我得到的XML 是&lt;PlayerExtended id="51641" actions="" /&gt;。请参阅:dotnetfiddle.net/mfWs4i 您能否在edit 您的问题中包含一个minimal reproducible example,以显示您是如何生成 XML 的?

标签: c# xml string serialization xml-attribute


【解决方案1】:

您是如何生成 XML 的?我似乎无法重现您的问题。

    public class Program
    {
        public static void Main(string[] args)
        {
            using var writer = new StringWriter();
            var serializer = new XmlSerializer(typeof(Player));
            serializer.Serialize(writer, new Player { Name = "", Age = 25 });
            Console.WriteLine(writer);
        }
    }

    public class Player
    {
        [XmlAttribute("name")]
        public string Name { get; set; }


        [XmlAttribute("age")]
        public int Age { get; set; }
    }

上面的代码以您想要的格式生成 name 属性 (name="")。让我知道这个答案对你来说是否足够。

【讨论】:

    【解决方案2】:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Xml.Serialization;
    
    // Runtime Target = .NET Core v2.1 or .NET Core v3.1
    
    namespace XmlSerialize
    {
        class Program
        {
            static void Main(string[] args)
            {
                var mickey = new Employee { FirstName = "Mickey", LastName = "Mouse" };
                var asterix = new Employee { FirstName = "Asterix", LastName = "" };
                var obelix = new Employee { FirstName = "Obelix", LastName = null };
                var nixnix = new Employee { FirstName = null, LastName = null };
    
                Console.WriteLine(SerializeXml(mickey) + SerializeXml(asterix) + SerializeXml(obelix) + SerializeXml(nixnix));
            }
    
            public static string SerializeXml<T>(T instanceToSerialize)
            {
                var serializer = new XmlSerializer(instanceToSerialize.GetType(), string.Empty);
                var result = string.Empty;
                using (var stringWriter = new StringWriter())
                {
                    serializer.Serialize(stringWriter, instanceToSerialize);
                    result = stringWriter.ToString();
                }
                return result;
            }
        }
    
        [XmlRoot("Employee")]
        public sealed class Employee
        {
            [XmlAttribute("FirstName")]
            public string FirstName { get; set; }
    
            [XmlIgnore]
            public string LastName { get; set; }
    
            [XmlAttribute("LastName")]
            public string SerializableLastName // <------------ Might this help?
            {
                get { return this.LastName ?? string.Empty; }
                set { this.LastName = value; }
            }
    
            [XmlElement]
            public List<string> Skills { get; set; }
        }
    }
    

    输出

    <?xml version="1.0" encoding="utf-16"?>
    <Employee FirstName="Mickey" LastName="Mouse" />
    <Employee FirstName="Asterix" LastName="" />
    <Employee FirstName="Obelix" LastName="" />
    <Employee LastName="" />
    

    【讨论】:

      【解决方案3】:

      将属性值设置为string.Empty 即可。我正在使用XmlSerializer 将对象转换为 XML。如果我将属性设置为string.Empty,这将导致 XML 中的属性为空。这是一个例子

      public class TestClass
      {
          [XmlAttribute("test1")]
          public string test1 { get; set; }
          [XmlAttribute("test2")]
          public string test2 { get; set; }
      }
      
      var dd = new List<TestClass>();
      
      dd.Add( new TestClass() { test1 = "asdf", test2 = string.Empty }); //will generate empty attribute for test2
      dd.Add( new TestClass() { test1 = "asdf" }); //the attribute test2 will be ignored
      
      using (var stringwriter = new System.IO.StringWriter())
      {
         var serializer = new XmlSerializer(dd.GetType());
      
         serializer.Serialize(stringwriter, dd);
         Console.WriteLine( stringwriter.ToString());
      }
      

      输出

      <?xml version="1.0" encoding="utf-16"?>
      <ArrayOfTestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <TestClass test1="asdf" test2="" />
       <TestClass test1="asdf" />
      </ArrayOfTestClass>
      

      【讨论】:

      • 他的例子已经表明他正在使用一个空字符串
      • @Timmeh,上面的例子表明如果你使用XmlSerializer你会得到想要的结果
      • 我已经在 8 分钟前回答过了?
      • 完美@Timmeh。为您的帖子点赞
      • 我不知道 XmlSerializer 是否是发问者的解决方案 :shrug: ,估计如果他返回网站,他将不得不发表评论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 2022-10-23
      • 2023-03-04
      • 2021-12-27
      相关资源
      最近更新 更多