gpt4 book ai didi

c# - xml序列化——改变xml的序列化类型

转载 作者:太空宇宙 更新时间:2023-11-03 11:32:01 24 4
gpt4 key购买 nike

我有一个这样的结构:

public struct Vehicles
{
public string Name { get; set; }
public string Count { get; set; }
public List<Car> Cars { get; set; }
}

public struct Car
{
public string Name { get; set; }
public int Count { get; set; }
public List<Tire> Tires { get; set; }
}

public struct Tire
{
public string Brand { get; set; }
public int Count { get; set; }
public int UniqueCount { get; set; }
public List<Dimension> Dimensions { get; set; }
}

public struct Dimension
{
public string Size { get; set; }
public int AlternateSize { get; set; }
}

当我序列化“Vehicles”时,它就像:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org /2001/XMLSchema">
<Vehicles>
<Name>SuperVehicles</Name>
<Cars>
<Car>
<Name>BMW</Name>
<Count>29</Count>
<Tires>
<Tire>
<Name>DMZ</Name>
<Count>26</Count>
<UniqueCount>24</UniqueCount>
<Dimensions>
<Dimension>
<Size>70x570</Size>
<AlternateSize>70x580</AlternateSize>
</Dimension>
<Dimension>
<Size>60x570</Size>
<AlternateSize>60x580</AlternateSize>
</Dimension>
<Dimension>
<Size>50x570</Size>
<AlternateSize>50x580</AlternateSize>
</Dimension>
</Dimensions>
</Tire>
</Tires>
</Car>
</Cars>
</Vehicles>
</root>

现在的问题是,我想这样序列化它:

<root>
<vehicles vehicleName="superVehicles" vehicleCount="50" carName="BMW"
carCount="25" tireBrand="kamu" tireCount="15" tireUniqueCount="15"
dimensionSize="70x570" dimensionAlternateSize="70x580" />
<vehicles vehicleName="superVehicles" vehicleCount="35" carName="MERCEDES"
carCount="22" tireBrand="kamu" tireCount="12" tireUniqueCount="12"
dimensionSize="60x570" dimensionAlternateSize="60x580" />
<vehicles vehicleName="superVehicles" vehicleCount="35" carName="PORSCHE"
carCount="22" tireBrand="kamu" tireCount="12" tireUniqueCount="12"
dimensionSize="60x570" dimensionAlternateSize="60x580" />
</root>

我是否必须更改结构并避免分组,或者是否有任何方法可以为 xml 序列化创建模式以收集此结果。

总结:当我将根结构序列化为 xml 时,我在新标记中获取了所有子项,但我需要将它们作为实例的属性,该实例仅创建行的根(车辆在这种情况下)元素的计数到 xml。

最佳答案

需要手动序列化。

以下是使用 System.Xml.Linq 实现此功能的方法:

var xmlElementsVehicles  = new[]{
new XElement("vehicles ", new object[]
{
new XElement("vehicleName", "superVehicles"),
new XElement("vehicleCount", 35),
new XElement("carName", "PORSCHE"),
new XElement("carCount", 2)
}),
new XElement("vehicles ", new object[]
{
new XElement("vehicleName", "superVehicles"),
new XElement("vehicleCount", 35),
new XElement("carName", "PORSCHE"),
new XElement("carCount", 2)
})
};
var root = new XElement("root", xmlElementsVehicles );
var myXml = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), root);
using (var xmlWriter = XmlWriter.Create(stream))
{
myXml.Save(xmlWriter);
}

关于c# - xml序列化——改变xml的序列化类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7455324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com