Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

c# - Change xml element value dynamically

[XmlRoot(ElementName="api_response")]
public class ApiResponse 
{
        [XmlElement( ElementName = "api_name")]
        public string api_name { get; set; }
}

Above is a class with specified class

I want to change ElementName="api_response"

api_response value to dynamic values like

some time it should be

ElementName="first response"

or

ElementName="second response"

I have to change this dynamically

I have tried some thing like this but dint get worked out

 XmlAttributeOverrides config1 = new XmlAttributeOverrides();
 config1.Add(typeof(ORM.ApiResponse), "ElementName",new XmlAttributes {XmlDefaultValue = "myvalue" };

but its not working

please help

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you are looking for serialization, this will do:

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

Edit:

To return a string, you can use a 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...