我有可自定义的对象类我想序列化:
public partial class CustomObject
{
public List<CustomProperty> Properties;
}
public class CustomProperty
{
public object Value;
[XmlAttribute]
public string Name;
}
// some class to be used as a value for CustomProperty
public class Person
{
public string Name;
public string Surname;
public string Photo;
[XmlAttribute]
public int Age;
}
目前,XML序列化输出如下所示:
<CustomObject>
<Properties>
<CustomProperty Name="Employer">
<Value p6:type="Person" xmlns:p6="http://www.w3.org/2001/XMLSchema-instance" Age="30">
<Name>John</Name>
<Surname>Doe</Surname>
<Photo>photos/John.jpg</Photo>
</Value>
</CustomProperty>
<CustomProperty Name="Desc">
<Value xmlns:q1="http://www.w3.org/2001/XMLSchema" p7:type="q1:string" xmlns:p7="http://www.w3.org/2001/XMLSchema-instance">some text</Value>
</CustomProperty>
</Properties>
</CustomObject>
首先,我想删除命名空间和所有噪音。
最终结果应如下所示:
<CustomObject>
<Properties>
<CustomProperty Name="Employer">
<Person Age="30">
<Name>John</Name>
<Surname>Doe</Surname>
<Photo>photos/John.jpg</Photo>
</Person>
</CustomProperty>
<CustomProperty Name="Desc">
<string>some text</string>
</CustomProperty>
</Properties>
</CustomObject>
或者这个:
<CustomObject>
<Properties>
<Person Name="Employer" Age="30">
<Name>John</Name>
<Surname>Doe</Surname>
<Photo>photos/John.jpg</Photo>
</Person>
<string Name="Desc">
some text
</string>
</Properties>
</CustomObject>
如何让XmlSerializer像这样输出它?
答案 0 :(得分:1)
查看XmlElement属性 - 这可能至少可以部分解决您的问题。来自MSDN:
public class Things {
[XmlElement(DataType = typeof(string)),
XmlElement(DataType = typeof(int))]
public object[] StringsAndInts;
}
将产生
<Things>
<string>Hello</string>
<int>999</int>
<string>World</string>
</Things>
答案 1 :(得分:1)
您还可以指定元素名称以确保正确处理类型:
[System.Xml.Serialization.XmlElementAttribute("files", typeof(Files))]
[System.Xml.Serialization.XmlElementAttribute("metrics", typeof(Metrics))]
public object[] Items { get; set; }
答案 2 :(得分:1)
您可以删除
之类的命名空间 StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
XmlSerializer serializer = new XmlSerializer(typeof(WSOpenShipments), myns);
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, "");
serializer.Serialize(writer, OS, ns);
xmlString = sb.ToString();
使用这个 - ns.Add(string.Empty,“”);