Arrayname on C # XML Serialization

[XmlRootAttribute("Order",IsNullable = false)]    
public class Order
{
    [XmlAttribute("pay_method")]
    public string paymethod { get; set; }

    [XmlAttribute("name")]
    public string custid { get; set; }

    [XmlArray("")]
    [XmlArrayItem("Cargo", IsNullable = false)]
    public Cargo[] Cargos { get; set; }

    [XmlArray("")]
    [XmlArrayItem("AddedService", IsNullable = false)]
    public AddedService[] AddedServices { get; set; }
}

XmlSerializer xs = new XmlSerializer();
var requeststring = xs.Serialize(request);

When I run this function, as a result, I always get <Cargos>as follows:

<Order pay_method="" custid="">
    <Cargos>
    <Cargo name=""/>
    <Cargo name=""/>
    </Cargos>
    <AddedServices>
        <AddedService name=""/>
        <AddedService name=""/>
    </AddedServices>
</Order>

I want to get the result without <Cargos></Cargos></AddedServices><AddedServices>and, for example:

<Order pay_method="" custid="">
    <Cargo name=""/>
    <Cargo name=""/>
    <AddedService name=""/>
    <AddedService name=""/>
</Order>

How can I configure both:

public Cargo[] Cargos { get; set; } 

public AddedService[] AddedServices { get; set; }
+4
source share
1 answer

You should not work with [XmlArrayItem], and then work with[XmlElement(ElementName = "...")]

This should match the expected XML:

[XmlRoot(ElementName = "Cargo")]
public class Cargo
{
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName = "AddedService")]
public class AddedService
{
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
}

[XmlRoot(ElementName = "Order")]
public class Order
{
    [XmlElement(ElementName = "Cargo")]
    public List<Cargo> Cargo { get; set; }
    [XmlElement(ElementName = "AddedService")]
    public List<AddedService> AddedService { get; set; }
    [XmlAttribute(AttributeName = "pay_method")]
    public string Pay_method { get; set; }
    [XmlAttribute(AttributeName = "custid")]
    public string Custid { get; set; }
}

edit Just tried (and it works):

class Program
{
    static void Main(string[] args)
    {
        XmlSerializer xsSubmit = new XmlSerializer(typeof(Order));
        var subReq = new Order { Cargo  = new List<Cargo>{new Cargo { Name = "test" }, new Cargo { Name = "foo" }}, AddedService = new List<AddedService>{new AddedService{Name="addedService"}}, Custid = "custId", Pay_method = "bla"};
        var xml = "";

        using (var sww = new StringWriter())
        {
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                xsSubmit.Serialize(writer, subReq);
                xml = sww.ToString(); // Your XML
            }
        }
    }
}

Output ( xml-variable):

<Order pay_method="bla" custid="custId">
    <Cargo name="test" />
    <Cargo name="foo" />
    <AddedService name="addedService" />
</Order>
+2
source

Source: https://habr.com/ru/post/1686107/


All Articles