XmlSerializer - 使用c#从xml输出中删除类名作为父元素

时间:2018-01-09 12:18:06

标签: c# xml xmlserializer

我正在尝试在c#中序列化一个类,但输出并不是我想要的。我想摆脱输出xml中的一个元素 - 类名 - 随序列化而来。

我的课程是:

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

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

我的代码是:

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

我得到的输出是:

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

xml输出(正文)我在后面是:

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

1 个答案:

答案 0 :(得分:0)

当我找到解决方案时,我自己回答:

 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;

我为对象类ObjKompParam子节点创建了新变量,并添加了子节点作为后代。