XML attribute not getting namespace prefix

前端 未结 4 1203
说谎
说谎 2020-12-12 00:01

I need to generate the following XML during serialization: (fragment)


  

        
4条回答
  •  旧时难觅i
    2020-12-12 00:20

    I did some research may be following answer helps

    For Attributes to have namespace prefix you have to specify a different namespace tag other than what you have specified http://foo. Following code hopefully will solve your issue. In the code i have remove the namespace for elements and added only for the attribute.

    public class IncidentEvent
    {
        public string EventDate { get; set; }
        public string EventTime { get; set; }
    
        [XmlAttribute("EventTypeText", Namespace = "http://foo")]
        public string EventTypeText { get; set; }
    
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            IncidentEvent xmlObj = new IncidentEvent()
            {
                EventDate = "2012.12.01",
                EventTime = "1:00:00",
                EventTypeText = "Beginining"
            };
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("ett", "http://foo");
            XmlSerializer serializer = new XmlSerializer(typeof(IncidentEvent));
            serializer.Serialize(Console.OpenStandardOutput(), xmlObj, ns);
            Console.WriteLine();
        }
    }
    

    http://www.w3.org/TR/2009/REC-xml-names-20091208/#defaulting

提交回复
热议问题