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

当我运行这个函数时,在结果中我总是得到这样的 <Cargos>:

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

我只想在没有 <Cargos></Cargos></AddedServices><AddedServices> 的情况下获得结果,例如:

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

我如何配置两者:
public Cargo[] Cargos { get; set; }

public AddedService[] AddedServices { get; set; }

最佳答案

那么你不应该使用 [XmlArrayItem],而是使用 [XmlElement(ElementName = "...")]
这应该与您预期的 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; }
}

编辑:
刚刚尝试过(并且有效):
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
            }
        }
    }
}

输出(xml -变量):

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

关于c# - C#语言中关于XML序列化的Arrayname,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46339241/

10-08 20:32