这是我的类结构:
[Serializable]
[XmlRoot("ClientRequestAPI3")]
public class RequestModelAPI3
{
[XmlElement("source")]
public string Source { get; set; }
[XmlElement("destination")]
public string Destination { get; set; }
[XmlArray("packages")]
public Packages[] Packages { get; set; }
}
[Serializable]
[XmlRoot("packages")]
public class Packages
{
[XmlElement("package")]
public int Package { get; set; }
}
它生成的XML是:
<?xml version="1.0" encoding="utf-16"?>
<ClientRequestAPI3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<source>Custom Source</source>
<destination>Custom Destination</destination>
<packages>
<Packages>
<package>1</package>
</Packages>
<Packages>
<package>3</package>
</Packages>
</packages>
</ClientRequestAPI3>
但是我要找的是:
<?xml version="1.0" encoding="utf-16"?>
<ClientRequestAPI3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<source>Custom Source</source>
<destination>Custom Destination</destination>
<packages>
<package>1</package>
<package>3</package>
</packages>
</ClientRequestAPI3>
那么缺少什么以便我可以像上面那样序列化它呢?
提前感谢,我非常感谢你的时间来研究它。
类似于
[Serializable]
[XmlRoot("ClientRequestAPI3")]
public class RequestModelAPI3
{
[XmlElement("source")]
public string Source { get; set; }
[XmlElement("destination")]
public string Destination { get; set; }
[XmlArray("packages")]
[XmlArrayItem("package")]
public Packages[] Packages { get; set; }
}
[Serializable]
public class Packages
{
[XmlText]
public int Package { get; set; }
}
但是[XmlText]和额外的类对我来说似乎有点臭…
我认为最好将packages数组声明为int数组:
[XmlArray("packages")]
[XmlArrayItem("package")]
public int[] Packages { get; set; }
尝试如下:
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
namespace XmlSerializationFD
{
[XmlRoot("ClientRequestAPI3")]
public class RequestModelAPI3
{
[XmlElement("source", Order = 1)]
public string Source { get; set; }
[XmlElement("destination", Order = 2)]
public string Destination { get; set; }
[XmlElement("packages", Order = 3)]
public PackageInfo Packages = new PackageInfo();
}
public class PackageInfo
{
[XmlElement("package")]
public List<int> Package { get; set; } = new List<int>();
public void AddPackage(int id)
{
this.Package.Add(id);
}
}
}