Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a custom object which has a string property called 'Name' I'd like to keep the XML generated by serialization the same but add an attribute to the element called 'NiceName' with a value of 'Full name'.

This is what i have currently:

<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 XSLT so i don't want to change the way the class works if possible. I.E. Changing name from string to a custom class. All objects will have the same attribute it will never change it is going to be totally read only.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
643 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use a combination of XMLAttribute and XmlText()

take below example of 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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...