C# 将类的一部分编写为XML
你好,我想问你一个问题 我创建了一个Person类,并编写了Person名称、姓氏、id和图像 现在我想用image将这个类保存为.xml。我找到了将类另存为.xml的解决方案,但它不会将任何图像保存到.xml文件中C# 将类的一部分编写为XML,c#,xml,C#,Xml,你好,我想问你一个问题 我创建了一个Person类,并编写了Person名称、姓氏、id和图像 现在我想用image将这个类保存为.xml。我找到了将类另存为.xml的解决方案,但它不会将任何图像保存到.xml文件中 private void SaveasXML() { XmlSerializer serializer = new XmlSerializer(typeof(BindingList<Person>)); FileStream fileStream =
private void SaveasXML()
{
XmlSerializer serializer = new XmlSerializer(typeof(BindingList<Person>));
FileStream fileStream = File.Create(Application.StartupPath + "\\Data\\Person.xml");
serializer.Serialize(fileStream, New_Xml_Person);
}
private void SaveasXML()
{
XmlSerializer serializer=新的XmlSerializer(typeof(BindingList));
FileStream FileStream=File.Create(Application.StartupPath+“\\Data\\Person.xml”);
serializer.Serialize(fileStream,New_Xml_Person);
}
我想将所有带有图像的信息保存到.xml文件中。要将图像另存为.xml文件,应将其转换为base64string
。我知道,但我不能用它
有什么建议吗?谢谢。您可以在Person类中添加byte[]ImageBuffer属性,该属性包含二进制图像数据。然后还可以在Image属性上设置XmlIgnore属性以抑制其(反)序列化,并在ImageBuffer属性上设置XmlElement(“Image”)以将其(反)序列化为Image 最新答复:
[XmlIgnoreAttribute()]
public Bitmap Picture { get { return picture; } set { picture = value; } }
[XmlElementAttribute("Picture")]
public byte[] PictureByteArray {
get {
if (picture != null) {
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
picture.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
return ms.ToArray();
}
} else return null;
}
set {
if (value != null)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(value))
{
picture = new Bitmap(Image.FromStream(ms));
}
}
else picture = null;
}
}
是否需要将实际图像保存到XML文件中,还是只保存路径?如何将图像存储在类中?。您可以共享您的Person clsss代码吗?图像可以另存为转换后的Base64String。my Person类的最后一个获取集部分:[XmlElementAttribute(“Picture”)]公共字节[]PictureByteArray{get{if(Picture!=null){TypeConverter BitmapConverter=TypeDescriptor.GetConverter(Picture.GetType());返回(byte[])BitmapConverter.ConvertTo(Picture,typeof(byte[]);}else return null;}set{if(value!=null)picture=new Bitmap(new MemoryStream(value));else picture=null;}}}我将文本更改为:[XmlIgnoreAttribute()]公共位图picture{get{return picture;}set{picture=value;}[xmlementattribute(“picture”)]公共字节[]PictureByteArray{get{if(picture!=null){TypeConverter BitmapConverter=TypeDescriptor.GetConverter(picture.GetType());return(byte[])BitmapConverter.ConvertTo(picture,typeof(byte[]);}else返回null;}set{if(value!=null)picture=新位图(新MemoryStream(value));else picture=null;}}}但它不起作用。它起作用了。非常感谢你,兄弟。你现在真的帮助了我。:)