You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET中反序列化XML后再序列化如何保留XSD的schemaLocation属性

如何在.NET XML序列化时保留xsi:schemaLocation属性

要解决序列化后丢失xsi:schemaLocation的问题,核心是在你的根模型类中显式定义对应这个属性的成员——默认的XmlSerializer不会自动处理这个属于XML实例命名空间的属性。下面是具体的修改步骤:

1. 修改VB.NET根模型类

在你的XmlStationSetpoints类中,添加一个对应xsi:schemaLocation的属性,并用XmlAttribute特性标记,指定正确的命名空间(http://www.w3.org/2001/XMLSchema-instance,也就是XML中的xsi前缀对应的命名空间):

<XmlRoot("StationSetpoints")>
Public Class XmlStationSetpoints
    <XmlElement("Setpoint")>
    Public Property Setpoints As List(Of XmlStationSetpointsSetpoint)
    
    ' 新增:映射xsi:schemaLocation属性
    <XmlAttribute("schemaLocation", Namespace:="http://www.w3.org/2001/XMLSchema-instance")>
    Public Property SchemaLocation As String
End Class

<Serializable>
Public Class XmlStationSetpointsSetpoint
    <XmlElement("Point")>
    Public Property Points As List(Of XmlStationSetpointsSetpointPoint)
    ' 其他属性保持不变...
End Class

2. 验证反序列化与序列化流程

修改模型后,你的现有C#代码不需要做额外调整:

  • 反序列化时,原始XML中的xsi:schemaLocation="http://www.w3schools.com StationSetpoints.xsd"会被自动读取到settings.SchemaLocation属性中;
  • 序列化时,XmlSerializer会自动将这个属性值写入回XML根元素的属性里。

测试后,序列化生成的XML会恢复你需要的schema路径:

<?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">
  <!-- 其他内容保持不变 -->
</StationSetpoints>

额外说明

如果需要动态修改schema路径,你也可以在序列化前手动给settings.SchemaLocation赋值,比如:

settings.SchemaLocation = "http://your-new-namespace NewSchema.xsd";

这样序列化后的XML就会使用你指定的新路径。

内容的提问来源于stack exchange,提问作者djv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:12:46