Add Xml attribute to string property

I have a custom object that has a string property called "Name". I would like to keep the serialization generated XML the same, but add an attribute to the element named "NiceName" with the value "Full Name".

This is what I have:

<TheObject> <Name>mr nobody</Name> </TheObject> 

This is what I would like to generate:

 <TheObject> <Name NiceName='Full name'>mr nobody</Name> </TheObject> 

I only need this for some XSLTs, so I don’t want to change the way the class works, if possible. I.E. Change the name from a string to a custom class. All objects will have the same attribute that it will never change, it will be fully read.

+7
c # xml serialization
source share
2 answers

You can use a combination of XMLAttribute and XmlText ()

take an example of a class declaration:

  public class Description { private int attribute_id; private string element_text; [XmlAttribute("id")] public int Id { get { return attribute_id; } set { attribute_id = value; } } [XmlText()] public string Text { get { return element_text; } set { element_text = value; } } } 

The output will be

 <XmlDocRoot> <Description id="1">text</Description> 

+7
source share

Perhaps if you define a different type, as shown below:

 public class Person { private string _name; [XmlIgnore] public string Name { get { return _name; } set { _name = value; ThePersonName = new PersonName() { Name = FullName, NiceName = _name }; } } [XmlElement(ElementName = "Name")] public PersonName ThePersonName { get; set; } public string FullName { get; set; } } public class PersonName { [XmlAttribute] public string NiceName { get; set; } [XmlText] public string Name { get; set; } } 

Using

  XmlSerializer s = new XmlSerializer(typeof(Person)); Person ali = new Person(); ali.FullName = "Ali Kheyrollahi"; ali.Name = "Nobody"; s.Serialize(new FileStream("ali.xml",FileMode.Create), ali); 

Will generate

 <?xml version="1.0"?> <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Name NiceName="Nobody">Ali Kheyrollahi</Name> <FullName>Ali Kheyrollahi</FullName> </Person> 
+4
source share

All Articles