Add Attribute to XMLROOT ElementName

Zaki picture Zaki · May 24, 2013 · Viewed 13.9k times · Source

I have a class with the class attribute :

[XmlRoot(ElementName = "RootXML")]
public class Apply
{
    /My Properties
}

now to create an xml from the above class I use below function :

public virtual string RenderXml()
{

    XmlTextWriter writer = null;
    try
    {
        MemoryStream ms = new MemoryStream();
        writer = new XmlTextWriter(ms, Encoding.UTF8);
        writer.Formatting = Formatting.Indented;
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        _xmlSerializer.Serialize(writer, this, ns);
        ms.Position = 0;
        using (StreamReader sr = new StreamReader(ms))
        {
            return sr.ReadToEnd();
        }
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

My question is how do i add attributes to "RootXML" and read the value of attribute from config file and from function e.g.

<RootXML attr1="read from config" attr2="read from function" >
    <Property1>value</Property1>
</RootXML>

Answer

Frank59 picture Frank59 · May 24, 2013

You can add to your class property attribute [XmlAttribute] and that property will be serilized as attribute

[XmlRoot(ElementName = "RootXML")]
public class Apply
{
    private string _testAttr="dfdsf";



    [XmlAttribute]
    public String TestAttr
    {
        get { return _testAttr; }

        set { _testAttr = value; }
    }
}

Serialization result for that class

<RootXML TestAttr="dfdsf" />

Added for last comment. If i understand correctly you need to have only one key in session. If it true, that you can use something like that:

string GetKey(){

      if (String.IsNullOrEmpty(HttpContext.Current.Session["mySessionKey"].ToString()))
                HttpContext.Current.Session["mySessionKey"] = GenereteKey();
      return HttpContext.Current.Session["mySessionKey"].ToString();

}