[XmlRoot(ElementName="api_response")]
public class ApiResponse
{
[XmlElement( ElementName = "api_name")]
public string api_name { get; set; }
}
上面是一个具有指定类
的类我想更改 ElementName =" api_response"
api_response值为动态值,如
有一段时间应该是
ElementName="first response"
或
ElementName="second response"
我必须动态更改
我尝试过这样的事情但是得到了解决方法
XmlAttributeOverrides config1 = new XmlAttributeOverrides();
config1.Add(typeof(ORM.ApiResponse), "ElementName",new XmlAttributes {XmlDefaultValue = "myvalue" };
但它不起作用
请帮助
谢谢
答案 0 :(得分:1)
如果您正在寻找序列化,请执行以下操作:
var apiResponse = new ApiResponse() { api_name = "test api" };
using (var writer = XmlWriter.Create(@"apiData.xml"))
{
var ser = new System.Xml.Serialization.XmlSerializer(
typeof(ApiResponse), new XmlRootAttribute("newRoot"));
ser.Serialize(writer,apiResponse);
}
编辑:
要返回字符串,您可以使用stringwriter
。
var apiResponse = new ApiResponse() { api_name = "test api" };
using (stringwriter = new StringWriter())
{
var ser = new System.Xml.Serialization.XmlSerializer(
typeof(ApiResponse));
ser.Serialize(stringwriter,apiResponse);
var xmlString= stringwriter.GetStringBuilder().ToString();
return xmlString;
}