+-

我有一个带有class属性的类:
[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>
最佳答案
您可以将[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();
}
点击查看更多相关文章
转载注明原文:c#-将属性添加到XMLROOT ElementName - 乐贴网