我想要实现的目标看起来相当简单。
鉴于课程
public class Wrapper<T> {
T Data { get; set; }
bool Success { get;set; }
List<Error> Errors { get; set; }
}
我只想让Data参数的XML输出包含在<Data></Data>
标记中。
IE: 期望的输出:
<Wrapper>
<Data>
<Person first="Bob" last="Robertson"/>
</Data>
<Errors/>
<Success>true</Success>
</Wrapper
实际输出:
<Wrapper>
<Person first="Bob" last="Robertson"/>
<Errors/>
<Success>true</Success>
</Wrapper>
是否有一个简单的IXmlSerializable实现,我可以在大多数情况下单独保留序列化并只包装一个成员?
编辑:这是在WCF服务中,所以我(据我所知)没有权限创建XmlSerializer。
我最终做了什么:
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteElementString("Success", Success.ToString());
writer.WriteStartElement("Errors");
foreach (var error in Errors)
{
Util.XmlSerialize(error, writer);
}
writer.WriteStartElement("Data");
Util.XmlSerialize(this.Data, writer);
writer.WriteEndElement();
}
-
public class Util
{
public static void XmlSerialize<T>(T obj, XmlWriter writer)
{
var nsSerializer = new XmlSerializerNamespaces();
nsSerializer.Add("", "");
var ser = new XmlSerializer(typeof (T));
ser.Serialize(writer, obj, nsSerializer);
}
}
答案 0 :(得分:0)
您可以使用XmlOverrides:
var xmlOverrides = new XmlAttributeOverrides();
var attributes = new XmlAttributes();
attributes.XmlElements
.Add(new XmlElementAttribute("Person", typeof (Person)));
xmlOverrides.Add(typeof(Wrapper<Person>), "Data", attributes);
var serializer = new XmlSerializer(typeof(Wrapper<ExampleObject>), xmlOverrides);
答案 1 :(得分:0)
<强>模式强>
public class Wrapper<T>
{
public T Data { get; set; }
public bool Success { get; set; }
}
public class Person
{
public string first;
public string last;
}
XML序列化
Wrapper<Person> f = new Wrapper<Person>();
f.Data = new Person();
f.Data.first = "Bob";
f.Data.last = "Robertson";
XmlSerializer SerializerObj = new XmlSerializer(typeof(Wrapper<Person>));
TextWriter WriteFileStream = new StreamWriter(@"C:\test.xml");
SerializerObj.Serialize(WriteFileStream, f);
WriteFileStream.Close();
XML输出
<?xml version="1.0" encoding="utf-8"?>
<WrapperOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Data>
<first>Bob</first>
<last>Robertson</last>
</Data>
<Success>false</Success>
</WrapperOfPerson>