3

我有一个具有类属性的类:

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

现在从上面的类创建一个xml,我使用下面的函数:

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();
    }
}

我的问题是如何将属性添加到“RootXML”并从配置文件和函数中读取属性值,例如

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

1 回答 1

2

您可以添加到您的类属性属性[XmlAttribute],该属性将被序列化为属性

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



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

        set { _testAttr = value; }
    }
}

该类的序列化结果

<RootXML TestAttr="dfdsf" />

添加到最后的评论。如果我理解正确,您在会话中只需要一个键。如果是真的,你可以使用类似的东西:

string GetKey(){

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

}
于 2013-05-24T10:55:54.863 回答