I have a 클래스 C # 보유하고 있는 상속됨. 나는 built" 성공적으로 "; 개체. 하지만 XML 로 객체에는 직렬화할 해야 합니다. 쉽게 할 수 있나요?
마치 설정되었습니다 # 39 m 클래스, how to get 확실하지 않지만, I& 직렬화하지 위한 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
{
...
}
다음은 내가 할 수 있지만, 어떤 생각해봤죠 doesn& # 39, 빗나갔다.
MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();
Xml 표현을 어떻게 다운로드합니까 이 객체의?
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
}
}
내가 아닌 문자열 변수를 사용하여 아래 같은 수정되었음 내거냐 반환되기를 ref.
public static string Serialize<T>(this T value)
{
if (value == null)
{
return string.Empty;
}
try
{
var xmlserializer = new XmlSerializer(typeof(T));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
xmlserializer.Serialize(writer, value);
return stringWriter.ToString();
}
}
catch (Exception ex)
{
throw new Exception("An error occurred", ex);
}
}
사용 약간만이라도 다음과 같습니다.
var xmlString = obj.Serialize();
복사됩니다 저장 기능을 추가할 수 있습니다 다음 함수를 사용하여 모든 객체를 xml 시스템.1믈 이름공간이.
/// <summary>
/// Saves to an xml file
/// </summary>
/// <param name="FileName">File path of the new xml file</param>
public void Save(string FileName)
{
using (var writer = new System.IO.StreamWriter(FileName))
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(writer, this);
writer.Flush();
}
}
다음 기능 추가 및 교체 객체에는 저장한 파일을 만들 수 있는 개체 유형 [ObjectType] 를 만들 수 있습니다.
/// <summary>
/// Load an object from an xml file
/// </summary>
/// <param name="FileName">Xml file name</param>
/// <returns>The object created from the xml file</returns>
public static [ObjectType] Load(string FileName)
{
using (var stream = System.IO.File.OpenRead(FileName))
{
var serializer = new XmlSerializer(typeof([ObjectType]));
return serializer.Deserialize(stream) as [ObjectType];
}
}
확장명은 클래스:
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();
그냥 하고 싶은 파일에서 참조하는 이름공간이 너회의 확장명은 방법 및 it& # 39 에서 이를 사용하여, ll 작동합니까 (내 예 수 있을 것입니다. 미proje스텐시언스 사용하여 ',')
참고로 할 수 있는 유일한 방법은 스케쳐내 확장명은 관련된 특정 클래스 (예: someone@email. 'Foo'), 'T' 에 참가, 준우승을 인수 확장명은 방법을 바꿀 수 있습니다.
'공용 정적 구체화하십시오 직렬화할 (이 Foo 값) {}'.
아래와 같은 객체에는 직렬화된 XML 의 모든 기능을 사용할 수 있습니다.
public static bool Serialize<T>(T value, ref string serializeXml)
{
if (value == null)
{
return false;
}
try
{
XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
StringWriter stringWriter = new StringWriter();
XmlWriter writer = XmlWriter.Create(stringWriter);
xmlserializer.Serialize(writer, value);
serializeXml = stringWriter.ToString();
writer.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
이 client 에서 문의할 수 있습니다.
내가 답을 복제본에 벤 그리프카 함께 시작됩니다.
public void Save(string FileName)
{
using (var writer = new System.IO.StreamWriter(FileName))
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(writer, this);
writer.Flush();
}
}
내가 이 코드를 사용할 수 있다. 하지만 이 솔루션은 현실이 조금 문제가 있는 것으로 나타났다. 일반적으로 대부분의 프로그래머가 직렬화할 그냥 설정 저장 및 데즈리얼리즈 설정과 로드. 이는 낙관적인 책정안. 일단 어떤 이유로 인해, 일부 기록되었으므로 직렬화하지 못했습니다 파일이 XML 파일을 완료되지 않은 것은 잘못된. Xml 의 응용 프로그램을 사용할 수 없으며 낮음-1 역직렬화를 때 손상됨 5월 시작. 아니다, 내가 먼저 큰 파일의 경우, '다음' 미모리스트림 제안하세요 직렬화할 객체를 기록하십시오 스트림을 절실해졌습니다. 이 경우 복잡한 사용자 정의 직렬화하지 는 몇 가지 경우에 특히 중요합니다. 모든 경우에 테스트할 수 없다.
public void Save(string fileName)
{
//first serialize the object to memory stream,
//in case of exception, the original file is not corrupted
using (MemoryStream ms = new MemoryStream())
{
var writer = new System.IO.StreamWriter(ms);
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(writer, this);
writer.Flush();
//if the serialization succeed, rewrite the file.
File.WriteAllBytes(fileName, ms.ToArray());
}
}
이것은 파일, 함께 할 수 있는 현실 세계를 책정안 역직렬화를 손상됨 직렬화하지 언젠가는. 로드 기능을 제공하는 벤 그리프카 정상입니다.
public static [ObjectType] Load(string fileName)
{
using (var stream = System.IO.File.OpenRead(fileName))
{
var serializer = new XmlSerializer(typeof([ObjectType]));
return serializer.Deserialize(stream) as [ObjectType];
}
}
및 복구 책정안 랩된 정도 걸릴 수 있다. 설정 파일 또는 기타 파일을 삭제할 수 있는 적합한 것이 문제 발생 시.
public static [ObjectType] LoadWithRecovery(string fileName)
{
try
{
return Load(fileName);
}
catch(Excetion)
{
File.Delete(fileName); //delete corrupted settings file
return GetFactorySettings();
}
}
객체를 직렬화할 위해 해야 할 것:
using (StreamWriter myWriter = new StreamWriter(path, false))
{
XmlSerializer mySerializer = new XmlSerializer(typeof(your_object_type));
mySerializer.Serialize(myWriter, objectToSerialize);
}
또한 위해 일할 수 있다는 사실을 주지하십시오 스마일즈리얼리처 파라메트리스 구성자를 필요합니다.
public string SerializeObject(object obj)
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
serializer.Serialize(ms, obj);
ms.Position = 0;
xmlDoc.Load(ms);
return xmlDoc.InnerXml;
}
}
string FilePath = ConfigurationReader.FileLocation; //Getting path value from web.config
XmlSerializer serializer = new XmlSerializer(typeof(Devices)); //typeof(object)
MemoryStream memStream = new MemoryStream();
serializer.Serialize(memStream, lstDevices);//lstdevices : I take result as a list.
FileStream file = new FileStream(folderName + "\\Data.xml", FileMode.Create, FileAccess.ReadWrite); //foldername:Specify the path to store the xml file
memStream.WriteTo(file);
file.Close();
그 결과 원하는 위치에 xml 파일로 만들어 저장할 수 있습니다.
내 업종에문제가 코드입니다. Utf8 xlm 활성화하십시오 되돌려줍니다 빈 이름공간이.
// override StringWriter
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
private string GenerateXmlResponse(Object obj)
{
Type t = obj.GetType();
var xml = "";
using (StringWriter sww = new Utf8StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
var ns = new XmlSerializerNamespaces();
// add empty namespace
ns.Add("", "");
XmlSerializer xsSubmit = new XmlSerializer(t);
xsSubmit.Serialize(writer, obj, ns);
xml = sww.ToString(); // Your XML
}
}
return xml;
}
예 되돌려줍니다 응답 얀덱스 apiu 결제 통보함 url:
<?xml version="1.0" encoding="utf-8"?><paymentAvisoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" performedDatetime="2017-09-01T16:22:08.9747654+07:00" code="0" shopId="54321" invoiceId="12345" orderSumAmount="10643" />
I have a 직렬화할 매우 간단한 방법을 사용하여 객체를 XML, C #, # 39 의 높은 it& 작동하잖아 멋지구리해요 및 재사용 가능한. 이것은 내가 하고 싶은 사람이 있지만, 이 때문에 기존 그러니까말이야 스레드할 게시물로의 그들에게 이 도움됐네 볼 수도 있다.
다음은 내가 어떻게 security. 방법:
var objectToSerialize = new MyObject();
var xmlString = objectToSerialize.ToXmlString();
다음은 클래스를 높여줍니까 작동합니까:
using System.IO;
using System.Xml.Serialization;
public static class XmlTools
{
public static string ToXmlString<T>(this T input)
{
using (var writer = new StringWriter())
{
input.ToXml(writer);
return writer.ToString();
}
}
private static void ToXml<T>(this T objectToSerialize, StringWriter writer)
{
new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
}
}
using System;
public class clsPerson
{
public string FirstName;
public string MI;
public string LastName;
}
class class1
{
static void Main(string[] args)
{
clsPerson p=new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}