简体   繁体   中英

XmlSerializer and controlling namespace in XmlAnyElement

using dotnet 2.0. Code to illustrate :

        Class1 c1 = new Class1(); 
        c1.SomeInt = 5;

        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<anode xmlns=\"xyz\" ><id>123</id></anode>");  

        c1.Any = new XmlElement[1];
        c1.Any[0] = (XmlElement)doc.DocumentElement;

        XmlSerializer ser = new XmlSerializer(typeof(Class1));
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "xyz");

        StringBuilder sb = new StringBuilder();
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;

        XmlWriter writer = XmlWriter.Create(sb, settings);
        writer.WriteStartElement("root");
        ser.Serialize(writer, c1, ns);
        writer.WriteEndElement();

        writer.Close();

        string str = sb.ToString();
        MessageBox.Show(str);

where Class1 is defined like :

[System.Serializable()]
[System.Xml.Serialization.XmlRoot(Namespace="xyz")]
public class Class1
{
    private int someInt;

    public int SomeInt
    {
        get { return someInt; }
        set { someInt = value; }
    }

    private System.Xml.XmlElement[] anyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAnyElementAttribute()]
    public System.Xml.XmlElement[] Any
    {
        get
        {
            return this.anyField;
        }
        set
        {
            this.anyField = value;
        }
    }
}

This code displays the string :

<root><Class1 xmlns="xyz"><SomeInt>5</SomeInt><anode xmlns="xyz"><id>123</id></anode></Class1></root>

This is the correct xml, but I'm wondering if this can be simplified.

What I would like is to not have the redundant xmlns="xyz" part in the "anode" element. ie I would like :

<root><Class1 xmlns="xyz"><SomeInt>5</SomeInt><anode><id>123</id></anode></Class1></root>

Is this possible ?

No, I don't believe you can. You could use an aliased namespace as described in this article: Prettification of XML Serialization within Web Services .

settings.NamespaceHandling = NamespaceHandling.OmitDuplicates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM