【发布时间】:2021-11-28 18:50:34
【问题描述】:
我将一个 Xml 文件反序列化为一个 .NET 类,修改属性,然后序列化回同一个文件。这是 .NET 模型 (vb.net)
<XmlRoot("StationSetpoints")>
Public Class XmlStationSetpoints
<XmlElement("Setpoint")>
Public Property Setpoints As List(Of XmlStationSetpointsSetpoint)
End Class
<Serializable>
Public Class XmlStationSetpointsSetpoint
<XmlElement("Point")>
Public Property Points As List(Of XmlStationSetpointsSetpointPoint)
' etc...
End Class
反序列化和序列化(c#)
var settings = New XmlStationSetpoints();
var serializer = New XmlSerializer(XmlStationSetpoints);
// deserialize
using StreamReader sr = new StreamReader(path)
settings = (XmlStationSetpoints)serializer.Deserialize(sr);
// serialize
using StreamWriter sw = new StreamWriter(path, false)
serializer.Serialize(sw, settings);
原始 Xml 文件,包括位于 Xml 文件 xsi:schemaLocation="http://www.w3schools.com StationSetpoints.xsd" 旁边的本地架构文件(第 5 行)
<?xml version="1.0" encoding="utf-8"?>
<StationSetpoints
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xsi:schemaLocation="http://www.w3schools.com StationSetpoints.xsd">
<Setpoint PartNumber="108022">
<Point InstrumentName="PD Stage" Value="10"/>
</Setpoint>
<Setpoint PartNumber="107983">
<Point Order="2" InstrumentName="PD Stage" Value="7.5"/>
</Setpoint>
</StationSetpoints>
当文件被序列化时,该架构路径不包括在内
<?xml version="1.0" encoding="utf-8"?>
<StationSetpoints
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Setpoint PartNumber="108022">
<Point Order="0" InstrumentName="PD Stage" Value="10"></Point>
</Setpoint>
<Setpoint PartNumber="107983">
<Point Order="2" InstrumentName="PD Stage" Value="7.5"></Point>
</Setpoint>
</StationSetpoints>
如何在 .NET 类中保留该架构路径,以便序列化文件包含它?
【问题讨论】:
标签: c# xml vb.net xml-serialization