views:

446

answers:

2

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. i.e. I would like :

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

Is this possible ? TIA

+1  A: 

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.

Mitch Wheat
A: 
settings.NamespaceHandling = NamespaceHandling.OmitDuplicates
Nick Whaley