向序列化的XML元素添加前缀

本文关键字:添加 加前缀 元素 XML 序列化 | 更新日期: 2023-09-27 18:09:17

我有以下实现IXmlSerializable的类:

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Xml.Serialization.XmlSchemaProviderAttribute("ExportSchema")]
[System.Xml.Serialization.XmlRootAttribute(IsNullable = false)]
public partial class ExceptionReport : object, System.Xml.Serialization.IXmlSerializable
{
    private System.Xml.XmlNode[] nodesField;
    private static System.Xml.XmlQualifiedName typeName = new System.Xml.XmlQualifiedName("ExceptionReport", "http://www.opengis.net/ows");
    public System.Xml.XmlNode[] Nodes
    {
        get
        {
            return this.nodesField;
        }
        set
        {
            this.nodesField = value;
        }
    }
    public void ReadXml(System.Xml.XmlReader reader)
    {
        this.nodesField = System.Runtime.Serialization.XmlSerializableServices.ReadNodes(reader);
    }
    public void WriteXml(System.Xml.XmlWriter writer)
    {
        System.Runtime.Serialization.XmlSerializableServices.WriteNodes(writer, this.Nodes);
    }
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }
    public static System.Xml.XmlQualifiedName ExportSchema(System.Xml.Schema.XmlSchemaSet schemas)
    {
        System.Runtime.Serialization.XmlSerializableServices.AddDefaultSchema(schemas, typeName);
        return typeName;
    }
}

抛出如下错误:

throw new FaultException<ExceptionReport>(exceptions.GetExceptionReport(), new FaultReason("A server exception was encountered."), new FaultCode("Receiver"));

我在soap错误细节中得到以下XML:

...
<detail>
    <ExceptionReport xmlns="http://www.opengis.net/ows">
        <ows:Exception exceptionCode="NoApplicableCode" locator="somewhere" xmlns:ows="http://www.opengis.net/ows">
            <ows:ExceptionText>mymessage</ows:ExceptionText>
        </ows:Exception>
    </ExceptionReport>
</detail>
...

但我真正想要的是"ows"前缀也在根ExceptionReport元素:

...
<detail>
    <ows:ExceptionReport xmlns:ows="http://www.opengis.net/ows">
        <ows:Exception exceptionCode="NoApplicableCode" locator="somewhere" xmlns:ows="http://www.opengis.net/ows">
            <ows:ExceptionText>mymessage</ows:ExceptionText>
        </ows:Exception>
    </ows:ExceptionReport>
</detail>
...

如何添加该前缀?

向序列化的XML元素添加前缀

如何为ExceptionReport添加属性并使用XmlNamespaceDeclarationsAttribute进行装饰,并在ExceptionReport类上设置XmlRoot属性的Namespace属性,如下所示:

...
[XmlRoot(IsNullable = false, Namespace = "http://www.opengis.net/ows")]
public partial class ExceptionReport
{
    [XmlNamespaceDeclarations()]
    public XmlSerializerNamespaces xmlns
    {
       get
       {
           XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
           xmlns.Add("ows", "http://www.opengis.net/ows");
           return xmlns;
       }
       set
       { 
       }
   }
   ...
}

当然,您可以在您的构造函数或任何您喜欢的地方填充名称空间,关键是要有一个返回适当的XmlSerializerNamespaces实例的属性。