programing tip

객체를 XML 문자열로 변환

itbloger 2020. 10. 11. 09:14
반응형

객체를 XML 문자열로 변환


WebserviceTypeXSD 파일의 xsd.exe 도구에서 얻은 클래스 가 있습니다.

이제 WebServiceType개체 의 인스턴스를 문자열 로 deserialize하고 싶습니다 . 어떻게 할 수 있습니까?

MethodCheckTypePARAMS 같은 목적 갖는 WebServiceType어레이.

내 첫 번째 시도는 a XmlSerializer와 a로 직렬화하는 것과 같았 습니다 StringWriter(직렬화하는 동안 a를 사용했습니다 StringReader).

이것은 WebServiceType객체를 직렬화하는 방법입니다 .

XmlSerializer serializer = new XmlSerializer(typeof(MethodCheckType));
        MethodCheckType output = null;
        StringReader reader = null;

        // catch global exception, logg it and throw it
        try
        {
            reader = new StringReader(path);
            output = (MethodCheckType)serializer.Deserialize(reader);
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            reader.Dispose();
        }

        return output.WebService;

편집하다:

다른 단어로 말할 수도 있습니다.이 MethodCheckType객체의 인스턴스가 있고 다른 한편으로는이 객체를 직렬화 한 XML 문서가 있습니다. 이제이 인스턴스를 문자열 형태의 XML 문서로 변환하고 싶습니다. 그런 다음 두 문자열 (XML 문서)이 동일한 지 증명해야합니다. XML 문서를 a로 읽고 StringReader이를 MethodCheckType객체 로 직렬화 하는 첫 번째 메서드의 단위 테스트를 수행하기 때문에이 작업을 수행해야 합니다.


다음은 두 가지 방법에 대한 변환 방법입니다. this = 클래스의 인스턴스

public string ToXML()
    {
        using(var stringwriter = new System.IO.StringWriter())
        { 
            var serializer = new XmlSerializer(this.GetType());
            serializer.Serialize(stringwriter, this);
            return stringwriter.ToString();
        }
    }

 public static YourClass LoadFromXMLString(string xmlText)
    {
        using(var stringReader = new System.IO.StringReader(xmlText))
        {
            var serializer = new XmlSerializer(typeof(YourClass ));
            return serializer.Deserialize(stringReader) as YourClass ;
        }
    }

나는 이것이 매우 오래된 게시물이라는 것을 알고 있지만 LB의 답변을 살펴본 후 수용 된 답변을 개선하고 내 응용 프로그램에 일반적으로 만들 수있는 방법에 대해 생각했습니다. 내가 생각 해낸 것은 다음과 같습니다.

public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new System.IO.StringWriter();
        var serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(stringwriter, dataToSerialize);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}

These methods can now be placed in a static helper class, which means no code duplication to every class that needs to be serialized.


    public static string Serialize(object dataToSerialize)
    {
        if(dataToSerialize==null) return null;

        using (StringWriter stringwriter = new System.IO.StringWriter())
        {
            var serializer = new XmlSerializer(dataToSerialize.GetType());
            serializer.Serialize(stringwriter, dataToSerialize);
            return stringwriter.ToString();
        }
    }

    public static T Deserialize<T>(string xmlText)
    {
        if(String.IsNullOrWhiteSpace(xmlText)) return default(T);

        using (StringReader stringReader = new System.IO.StringReader(xmlText))
        {
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
    }

This is my solution, for any list object you can use this code for convert to xml layout. KeyFather is your principal tag and KeySon is where start your Forech.

public string BuildXml<T>(ICollection<T> anyObject, string keyFather, string keySon)
    {
        var settings = new XmlWriterSettings
        {
            Indent = true
        };
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        StringBuilder builder = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(builder, settings))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement(keyFather);
            foreach (var objeto in anyObject)
            {
                writer.WriteStartElement(keySon);
                foreach (PropertyDescriptor item in props)
                {
                    writer.WriteStartElement(item.DisplayName);
                    writer.WriteString(props[item.DisplayName].GetValue(objeto).ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
            writer.WriteFullEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            return builder.ToString();
        }
    }

참고URL : https://stackoverflow.com/questions/11447529/convert-an-object-to-an-xml-string

반응형