我继承了一个c#类。我已经成功地“构建”了对象。但是我需要将对象序列化为XML。有什么简单的方法吗?
看起来类已经为序列化设置了,但我不确定如何获得XML表示。我的类定义是这样的:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)]
public partial class MyObject
{
...
}
以下是我认为我能做的,但它不起作用:
MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();
如何获得该对象的XML表示形式?
现在可能太晚了,但是只有用户定义的命名空间是序列化的:
public static string XmlSerialize<T>(this T obj) where T : class
{
Type serialType = typeof(T);
var xsSubmit = new XmlSerializer(serialType);
XmlWriterSettings xws = new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true };
var Namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, GetXmlNameSpace(serialType) ?? string.Empty )
});
private static string GetXmlNameSpace(Type target)
{
XmlRootAttribute attribute = (XmlRootAttribute)Attribute.GetCustomAttribute(target, typeof(XmlRootAttribute));
return attribute == null ? null : attribute.Namespace;
}
并在自定义类中定义命名空间
[XmlRoot("IdentityTerminal",Namespace = "http://my-name-space/XMLSchema")]
public class IdentityTerminal
{
}
这段代码允许只使用用户定义的名称空间,而忽略默认的名称空间。
扩展类:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace MyProj.Extensions
{
public static class XmlExtension
{
public static string Serialize<T>(this T value)
{
if (value == null) return string.Empty;
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter,new XmlWriterSettings{Indent = true}))
{
xmlSerializer.Serialize(xmlWriter, value);
return stringWriter.ToString();
}
}
}
}
}
用法:
Foo foo = new Foo{MyProperty="I have been serialized"};
string xml = foo.Serialize();
只是引用名称空间持有您的扩展方法在文件中,你想使用它,它将工作(在我的例子中,它将是:使用myproject . extensions;)
请注意,如果您想使扩展方法只特定于一个特定的类(例如。, Foo),你可以在扩展方法中替换T参数。
序列化(这个Foo值){…}
必须使用XmlSerializer进行XML序列化。下面是一个示例代码片段。
XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
var subReq = new MyObject();
var xml = "";
using(var sww = new StringWriter())
{
using(XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, subReq);
xml = sww.ToString(); // Your XML
}
}
根据泛型类的@kiquenet请求:
public class MySerializer<T> where T : class
{
public static string Serialize(T obj)
{
XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
using (var sww = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sww) { Formatting = Formatting.Indented })
{
xsSubmit.Serialize(writer, obj);
return sww.ToString();
}
}
}
}
用法:
string xmlMessage = MySerializer<MyClass>.Serialize(myObj);