2009-06-01 50 views
1

中的名稱空間。代碼來說明:XmlSerializer並使用dotnet 2.0控制XmlAnyElement

 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); 

,其中1類就像定義:

[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; 
     } 
    } 
} 

此代碼顯示字符串:

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

這是正確的XML,但我想知道,如果這可以簡化。

我想在「陽極」元素中沒有多餘的xmlns =「xyz」部分。 即我想要:

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

這可能嗎?

回答

0
settings.NamespaceHandling = NamespaceHandling.OmitDuplicates