使用dotnet 2.0。代码说明:
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);
其中Class1的定义如下:
[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 :(得分:1)
不,我不相信你能。您可以使用本文中所述的别名命名空间:Prettification of XML Serialization within Web Services。
答案 1 :(得分:0)
settings.NamespaceHandling = NamespaceHandling.OmitDuplicates