如何在C#类对象的XML根属性中添加多个命名空间?
解决C# XML序列化多命名空间问题
针对你提供的SOAP XML结构,以下是修正后的C#类,可正确序列化出包含多命名空间的XML:
using System.Xml.Serialization; [XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] public class Envelope { // 声明所有需要的命名空间 [XmlNamespaceDeclarations] public XmlSerializerNamespaces Xmlns { get; set; } = new XmlSerializerNamespaces(); [XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] public Header Header { get; set; } [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] public Body Body { get; set; } public Envelope() { // 初始化命名空间映射 Xmlns.Add("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); Xmlns.Add("", "http://test.com/v8_0"); // 默认命名空间 Xmlns.Add("SOAPENC", "http://schemas.xmlsoap.org/soap/encoding/"); Xmlns.Add("xsd", "http://www.w3.org/2001/XMLSchema"); Xmlns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); } } public class Header { // 可根据实际需求添加Header内的属性或元素 } public class Body { // 可根据实际需求添加Body内的属性或元素 }
关键说明:
- XmlRoot特性:指定根元素
Envelope的命名空间为SOAP-ENV的官方地址,与XML中的SOAP-ENV:Envelope匹配。 - XmlNamespaceDeclarations特性:标记
Xmlns属性,用于声明所有需要输出的命名空间映射,这是生成多命名空间的核心。 - XmlElement特性:为
Header和Body指定与根元素相同的SOAP-ENV命名空间,确保序列化后生成SOAP-ENV:Header、SOAP-ENV:Body格式的元素。 - 构造函数初始化:在构造函数中添加所有命名空间的前缀与URL映射,包括默认命名空间(前缀为空字符串)。
序列化示例代码:
如果需要将类实例序列化为XML字符串,可使用以下代码:
var envelope = new Envelope { Header = new Header(), Body = new Body() }; var serializer = new XmlSerializer(typeof(Envelope)); using var writer = new StringWriter(); serializer.Serialize(writer, envelope); var xmlString = writer.ToString();
运行后生成的XML将与你提供的示例结构完全一致,包含所有指定的命名空间。
内容的提问来源于stack exchange,提问作者Vijay Mandanka
相关产品推荐
相关产品推荐

