简体   繁体   中英

How to deserialize an REST POST xml request with a one row node that hase multiple attributes?

I need some help regarding deserialization of this kind of xml in C#:

<Request>
     <AccountStage att1="419749" att2="575474" att3="800177" att4="096057"  att5="917185" att6="017585" att7="huKuBgcQ" att8="stgs10" att9="ACTIVE" att10="2"   att11="2"/>
</Request>

If I use the "Special paste" feature from VS, and convert the request as xml classes, when I want to use the request and send it to the server, it changes the format as follows:

<Request>  
<AccountStage>
    <att1>22222</att1>    
    <att2>22222</att2>    
    <att3>22222</att3>    
    <att4>2</att4>    
    <att5>2</att5>   
    <att6>22222</att6>
    <att7>Ion</att7>    
    <att8>agg3</att8>    
    <att9>ACTIVE</att9>    
    <att10>2</att10>    
    <att11>2</att11>  
</AccountStage>
</Request> 

Use XmlAttribute to specify how members should be defined/interpreted:

using System.IO;
using System.Xml.Serialization;

namespace WpfApp2
{
    internal class Test
    {
        private readonly string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>

<Request>
  <AccountStage att1=""419749"" att2=""575474"" att3=""800177"" att4=""096057"" att5=""917185"" att6=""017585"" att7=""huKuBgcQ""
                att8=""stgs10"" att9=""ACTIVE"" att10=""2"" att11=""2"" />
</Request>";

        public Test()
        {
            Request request;

            // serialize
            var serializer = new XmlSerializer(typeof(Request));
            using (var reader = new StringReader(xml))
            {
                request = (Request) serializer.Deserialize(reader);
            }

            // deserialize

            request.AccountStage.Attribute1 = "abcd";

            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, request);
                var s = writer.ToString();
            }
        }
    }

    public class Request
    {
        public AccountStage AccountStage { get; set; }
    }

    public class AccountStage
    {
        [XmlAttribute("att1")]
        public string Attribute1 { get; set; }
    }
}

Result

<?xml version="1.0" encoding="utf-16"?>
<Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <AccountStage att1="abcd" />
</Request>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM