How to add namespace prefix for IXmlSerializable type

后端 未结 3 1998
执念已碎
执念已碎 2021-01-17 11:29

I have a following class definition

[XmlRoot(ElementName = \"person\",Namespace = \"MyNamespace\")]
public class Perso         


        
3条回答
  •  -上瘾入骨i
    2021-01-17 11:55

    Do you need to use XmlSerializer? If not, try following code:

    Person.cs

    Add new method:

    public void Serialize(XmlWriter writer)
    {
        writer.WriteStartDocument();
        writer.WriteStartElement("My", "Person", "MyNamespace");
        writer.WriteElementString("My", "FirstName", "MyNamespace", FirstName);
        writer.WriteElementString("My", "LastName", "MyNamespace", LastName);
        writer.WriteEndElement();
        writer.WriteEndDocument();
    }
    

    Usage

    var person = new Person { FirstName = "John", LastName = "Doe" };
    person.Serialize(new XmlTextWriter(Console.Out));
    

提交回复
热议问题