简体   繁体   中英

XmlSerializer - remove class name as parent element from xml output using c#

I am trying to serialize a class in c# but the output is not quite I am after. I want to get rid of one element in output xml - class name - that comes along with serialization.

My class is:

[XmlType("ADSobjotsing")]
public class ObjKompParam
{
    [XmlElement("aadressTekst")]
    public string Tekst;

    [XmlElement("adsOid")]
    public string OID;

My code is:

    protected override XElement ComposeQueryBody(object InputParams)
    {
        ObjKompParam param = (ObjKompParam)InputParams;

        var ads_o_q = new ObjKompParam();

        XElement body = new XElement(SOAPNS + "Body",
           new XElement(prod + "ADSobjotsing"));

        var ns = new XmlSerializerNamespaces();
        ns.Add("", "");

        XmlSerializer serializer = new XmlSerializer(typeof(ObjKompParam),"");

        XElement xe;
        using (var stream = new MemoryStream())
        {
            serializer.Serialize(stream, param, ns);
            stream.Position = 0;
            using (XmlReader reader = XmlReader.Create(stream))
            {
                xe = XElement.Load(reader);
            }
        }
            body.Descendants(prod + "ADSobjotsing").First().Add(new XElement(xe));

        return body;
    }

The output I get is:

<SOAP-ENV:Body>
    <prod:ADSobjotsing>
        <ADSobjotsing>
            <aadressTekst>Sügise 10</aadressTekst>
        </ADSobjotsing>
    </prod:ADSobjotsing>
</SOAP-ENV:Body>

The xml output (body) I am after is following:

<SOAP-ENV:Body>
    <prod:ADSobjotsing>
        <aadressTekst>Sügise 10</aadressTekst>
    </prod:ADSobjotsing>
</SOAP-ENV:Body>

I answer myself, as I worked out the solution:

 XmlSerializer serializer = new XmlSerializer(typeof(ObjKompParam),"");

        XElement xe;
        using (var stream = new MemoryStream()) //write into stream
        {
            serializer.Serialize(stream, param, ns); //writer, object
            stream.Position = 0;
            using (XmlReader reader = XmlReader.Create(stream))
            {
                xe = XElement.Load(reader);
            }
        }
        var child = xe.Descendants();
        body.Descendants(prod + "ADSobjotsing").First().Add(child);
        return body;

I made the new variable for object class ObjKompParam children and added children as descendants.

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