2016-06-03 1 views
0

HTTP 응답 XML 문서를 객체로 변환하려고합니다. 내가HTTP 응답 XML 문서를 C#의 개체로 변환하는 방법?

같은 유형의 처리되지 않은 예외 오류가 발생하고 역 직렬화하려고

은 'System.InvalidOperationException' 이가 system.xml.dll에서

추가 정보를 발생있다 XML 문서의 오류 (1, 2).

namespace Salcomp.SerialNumberStatus 
    { 
    public partial class Form1 : Form 
    { 
     MasterDataManagement MDM = new MasterDataManagement("http://localhost:8012/"); 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      XmlDocument doc = new XmlDocument(); 
      Salcomp.SerialNumberStatus.OperationType operationType = new Salcomp.SerialNumberStatus.OperationType(); 

      var test = MDM.RestGet<Salcomp.SerialNumberStatus.OperationType>("http://localhost/Enterprise/OperationTypes"); 

     } 
    } 
} 

역 직렬화를

public T RestGet<T>(string url) 
    { 
     if (!url.Contains("http://")) url = _mdmServerUrl + url; 
     var xDoc = url.HttpGet(); 
     var xml = xDoc.ToString(); 
     return XmlDeserializeFromString<T>(xml); 
    } 

    private T XmlDeserializeFromString<T>(string objectData) 
    { 
     return (T)XmlDeserializeFromString(objectData, typeof(T)); 
    } 

    private object XmlDeserializeFromString(string objectData, Type type) 
    { 
     XmlSerializer serializer = new XmlSerializer(type); 
     object result; 

     using (TextReader reader = new StringReader(objectData)) 
     { 
      result = serializer.Deserialize(reader); 
     } 
     return result; 
    } 

XML 응답 :

<OperationTypes xmlns="http://www.example.com/aaa/2011" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<OperationType Uri="http://localhost:8012/Enterprise/OperationTypes/a1d02dac-c454-497b-808d-a619009c7c7e" Name="test" Number="19" Active="true" Description="" SetupCalculation="PerWorkOrder" Side="" /> 
<OperationType Uri="http://localhost:8012/Enterprise/OperationTypes/07102c89-93e1-499b-980e-a61900cf2217" Name="OT_Prakash" Number="20" Active="false" Description="" SetupCalculation="PerWorkOrder" Side="" /> 
</OperationTypes> 
여기

namespace Salcomp.SerialNumberStatus 
{ 
using System; 
using System.Diagnostics; 
using System.Xml.Serialization; 
using System.Collections; 
using System.Xml.Schema; 
using System.ComponentModel; 
using System.IO; 
using System.Text; 
using System.Collections.Generic; 

public partial class OperationTypes 
{ 

    private List<OperationType> operationTypeField; 

    private static System.Xml.Serialization.XmlSerializer serializer; 

    public OperationTypes() 
    { 
     this.operationTypeField = new List<OperationType>(); 
    } 

    public List<OperationType> OperationType 
    { 
     get 
     { 
      return this.operationTypeField; 
     } 
     set 
     { 
      this.operationTypeField = value; 
     } 
    } 

    private static System.Xml.Serialization.XmlSerializer Serializer 
    { 
     get 
     { 
      if ((serializer == null)) 
      { 
       serializer = new System.Xml.Serialization.XmlSerializer(typeof(OperationTypes)); 
      } 
      return serializer; 
     } 
    } 

    #region Serialize/Deserialize 
    /// <summary> 
    /// Serializes current OperationTypes object into an XML document 
    /// </summary> 
    /// <returns>string XML value</returns> 
    public virtual string Serialize() 
    { 
     System.IO.StreamReader streamReader = null; 
     System.IO.MemoryStream memoryStream = null; 
     try 
     { 
      memoryStream = new System.IO.MemoryStream(); 
      Serializer.Serialize(memoryStream, this); 
      memoryStream.Seek(0, System.IO.SeekOrigin.Begin); 
      streamReader = new System.IO.StreamReader(memoryStream); 
      return streamReader.ReadToEnd(); 
     } 
     finally 
     { 
      if ((streamReader != null)) 
      { 
       streamReader.Dispose(); 
      } 
      if ((memoryStream != null)) 
      { 
       memoryStream.Dispose(); 
      } 
     } 
    } 

    /// <summary> 
    /// Deserializes workflow markup into an OperationTypes object 
    /// </summary> 
    /// <param name="xml">string workflow markup to deserialize</param> 
    /// <param name="obj">Output OperationTypes object</param> 
    /// <param name="exception">output Exception value if deserialize failed</param> 
    /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> 
    public static bool Deserialize(string xml, out OperationTypes obj, out System.Exception exception) 
    { 
     exception = null; 
     obj = default(OperationTypes); 
     try 
     { 
      obj = Deserialize(xml); 
      return true; 
     } 
     catch (System.Exception ex) 
     { 
      exception = ex; 
      return false; 
     } 
    } 

    public static bool Deserialize(string xml, out OperationTypes obj) 
    { 
     System.Exception exception = null; 
     return Deserialize(xml, out obj, out exception); 
    } 

    public static OperationTypes Deserialize(string xml) 
    { 
     System.IO.StringReader stringReader = null; 
     try 
     { 
      stringReader = new System.IO.StringReader(xml); 
      return ((OperationTypes)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); 
     } 
     finally 
     { 
      if ((stringReader != null)) 
      { 
       stringReader.Dispose(); 
      } 
     } 
    } 

    /// <summary> 
    /// Serializes current OperationTypes object into file 
    /// </summary> 
    /// <param name="fileName">full path of outupt xml file</param> 
    /// <param name="exception">output Exception value if failed</param> 
    /// <returns>true if can serialize and save into file; otherwise, false</returns> 
    public virtual bool SaveToFile(string fileName, out System.Exception exception) 
    { 
     exception = null; 
     try 
     { 
      SaveToFile(fileName); 
      return true; 
     } 
     catch (System.Exception e) 
     { 
      exception = e; 
      return false; 
     } 
    } 

    public virtual void SaveToFile(string fileName) 
    { 
     System.IO.StreamWriter streamWriter = null; 
     try 
     { 
      string xmlString = Serialize(); 
      System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); 
      streamWriter = xmlFile.CreateText(); 
      streamWriter.WriteLine(xmlString); 
      streamWriter.Close(); 
     } 
     finally 
     { 
      if ((streamWriter != null)) 
      { 
       streamWriter.Dispose(); 
      } 
     } 
    } 

    /// <summary> 
    /// Deserializes xml markup from file into an OperationTypes object 
    /// </summary> 
    /// <param name="fileName">string xml file to load and deserialize</param> 
    /// <param name="obj">Output OperationTypes object</param> 
    /// <param name="exception">output Exception value if deserialize failed</param> 
    /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> 
    public static bool LoadFromFile(string fileName, out OperationTypes obj, out System.Exception exception) 
    { 
     exception = null; 
     obj = default(OperationTypes); 
     try 
     { 
      obj = LoadFromFile(fileName); 
      return true; 
     } 
     catch (System.Exception ex) 
     { 
      exception = ex; 
      return false; 
     } 
    } 

    public static bool LoadFromFile(string fileName, out OperationTypes obj) 
    { 
     System.Exception exception = null; 
     return LoadFromFile(fileName, out obj, out exception); 
    } 

    public static OperationTypes LoadFromFile(string fileName) 
    { 
     System.IO.FileStream file = null; 
     System.IO.StreamReader sr = null; 
     try 
     { 
      file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); 
      sr = new System.IO.StreamReader(file); 
      string xmlString = sr.ReadToEnd(); 
      sr.Close(); 
      file.Close(); 
      return Deserialize(xmlString); 
     } 
     finally 
     { 
      if ((file != null)) 
      { 
       file.Dispose(); 
      } 
      if ((sr != null)) 
      { 
       sr.Dispose(); 
      } 
     } 
    } 
    #endregion 
} 

public partial class OperationType 
{ 

    private string uriField; 

    private string nameField; 

    private string numberField; 

    private bool activeField; 

    private bool activeFieldSpecified; 

    private string descriptionField; 

    private OperationSetupCalculation setupCalculationField; 

    private bool setupCalculationFieldSpecified; 

    private string sideField; 

    private bool usedForRoutingField; 

    private bool usedForSchedulingField; 

    private string categoryField; 

    private string skillsField; 

    private string aaa; 

    private static System.Xml.Serialization.XmlSerializer serializer; 

    public OperationType() 
    { 
     this.usedForRoutingField = false; 
     this.usedForSchedulingField = false; 
    } 

    public string Uri 
    { 
     get 
     { 
      return this.uriField; 
     } 
     set 
     { 
      this.uriField = value; 
     } 
    } 

    public string Name 
    { 
     get 
     { 
      return this.nameField; 
     } 
     set 
     { 
      this.nameField = value; 
     } 
    } 

    public string Number 
    { 
     get 
     { 
      return this.numberField; 
     } 
     set 
     { 
      this.numberField = value; 
     } 
    } 

    public bool Active 
    { 
     get 
     { 
      return this.activeField; 
     } 
     set 
     { 
      this.activeField = value; 
     } 
    } 

    [System.Xml.Serialization.XmlIgnoreAttribute()] 
    public bool ActiveSpecified 
    { 
     get 
     { 
      return this.activeFieldSpecified; 
     } 
     set 
     { 
      this.activeFieldSpecified = value; 
     } 
    } 

    public string Description 
    { 
     get 
     { 
      return this.descriptionField; 
     } 
     set 
     { 
      this.descriptionField = value; 
     } 
    } 

    public OperationSetupCalculation SetupCalculation 
    { 
     get 
     { 
      return this.setupCalculationField; 
     } 
     set 
     { 
      this.setupCalculationField = value; 
     } 
    } 

    [System.Xml.Serialization.XmlIgnoreAttribute()] 
    public bool SetupCalculationSpecified 
    { 
     get 
     { 
      return this.setupCalculationFieldSpecified; 
     } 
     set 
     { 
      this.setupCalculationFieldSpecified = value; 
     } 
    } 

    public string Side 
    { 
     get 
     { 
      return this.sideField; 
     } 
     set 
     { 
      this.sideField = value; 
     } 
    } 

    [System.ComponentModel.DefaultValueAttribute(false)] 
    public bool UsedForRouting 
    { 
     get 
     { 
      return this.usedForRoutingField; 
     } 
     set 
     { 
      this.usedForRoutingField = value; 
     } 
    } 

    [System.ComponentModel.DefaultValueAttribute(false)] 
    public bool UsedForScheduling 
    { 
     get 
     { 
      return this.usedForSchedulingField; 
     } 
     set 
     { 
      this.usedForSchedulingField = value; 
     } 
    } 

    public string Category 
    { 
     get 
     { 
      return this.categoryField; 
     } 
     set 
     { 
      this.categoryField = value; 
     } 
    } 

    public string Skills 
    { 
     get 
     { 
      return this.skillsField; 
     } 
     set 
     { 
      this.skillsField = value; 
     } 
    } 

    private static System.Xml.Serialization.XmlSerializer Serializer 
    { 
     get 
     { 
      if ((serializer == null)) 
      { 
       serializer = new System.Xml.Serialization.XmlSerializer(typeof(OperationType)); 
      } 
      return serializer; 
     } 
    } 

    #region Serialize/Deserialize 
    /// <summary> 
    /// Serializes current OperationType object into an XML document 
    /// </summary> 
    /// <returns>string XML value</returns> 
    public virtual string Serialize() 
    { 
     System.IO.StreamReader streamReader = null; 
     System.IO.MemoryStream memoryStream = null; 
     try 
     { 
      memoryStream = new System.IO.MemoryStream(); 
      Serializer.Serialize(memoryStream, this); 
      memoryStream.Seek(0, System.IO.SeekOrigin.Begin); 
      streamReader = new System.IO.StreamReader(memoryStream); 
      return streamReader.ReadToEnd(); 
     } 
     finally 
     { 
      if ((streamReader != null)) 
      { 
       streamReader.Dispose(); 
      } 
      if ((memoryStream != null)) 
      { 
       memoryStream.Dispose(); 
      } 
     } 
    } 

    /// <summary> 
    /// Deserializes workflow markup into an OperationType object 
    /// </summary> 
    /// <param name="xml">string workflow markup to deserialize</param> 
    /// <param name="obj">Output OperationType object</param> 
    /// <param name="exception">output Exception value if deserialize failed</param> 
    /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> 
    public static bool Deserialize(string xml, out OperationType obj, out System.Exception exception) 
    { 
     exception = null; 
     obj = default(OperationType); 
     try 
     { 
      obj = Deserialize(xml); 
      return true; 
     } 
     catch (System.Exception ex) 
     { 
      exception = ex; 
      return false; 
     } 
    } 

    public static bool Deserialize(string xml, out OperationType obj) 
    { 
     System.Exception exception = null; 
     return Deserialize(xml, out obj, out exception); 
    } 

    public static OperationType Deserialize(string xml) 
    { 
     System.IO.StringReader stringReader = null; 
     try 
     { 
      stringReader = new System.IO.StringReader(xml); 
      return ((OperationType)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); 
     } 
     finally 
     { 
      if ((stringReader != null)) 
      { 
       stringReader.Dispose(); 
      } 
     } 
    } 

    /// <summary> 
    /// Serializes current OperationType object into file 
    /// </summary> 
    /// <param name="fileName">full path of outupt xml file</param> 
    /// <param name="exception">output Exception value if failed</param> 
    /// <returns>true if can serialize and save into file; otherwise, false</returns> 
    public virtual bool SaveToFile(string fileName, out System.Exception exception) 
    { 
     exception = null; 
     try 
     { 
      SaveToFile(fileName); 
      return true; 
     } 
     catch (System.Exception e) 
     { 
      exception = e; 
      return false; 
     } 
    } 

    public virtual void SaveToFile(string fileName) 
    { 
     System.IO.StreamWriter streamWriter = null; 
     try 
     { 
      string xmlString = Serialize(); 
      System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); 
      streamWriter = xmlFile.CreateText(); 
      streamWriter.WriteLine(xmlString); 
      streamWriter.Close(); 
     } 
     finally 
     { 
      if ((streamWriter != null)) 
      { 
       streamWriter.Dispose(); 
      } 
     } 
    } 

    /// <summary> 
    /// Deserializes xml markup from file into an OperationType object 
    /// </summary> 
    /// <param name="fileName">string xml file to load and deserialize</param> 
    /// <param name="obj">Output OperationType object</param> 
    /// <param name="exception">output Exception value if deserialize failed</param> 
    /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> 
    public static bool LoadFromFile(string fileName, out OperationType obj, out System.Exception exception) 
    { 
     exception = null; 
     obj = default(OperationType); 
     try 
     { 
      obj = LoadFromFile(fileName); 
      return true; 
     } 
     catch (System.Exception ex) 
     { 
      exception = ex; 
      return false; 
     } 
    } 

    public static bool LoadFromFile(string fileName, out OperationType obj) 
    { 
     System.Exception exception = null; 
     return LoadFromFile(fileName, out obj, out exception); 
    } 

    public static OperationType LoadFromFile(string fileName) 
    { 
     System.IO.FileStream file = null; 
     System.IO.StreamReader sr = null; 
     try 
     { 
      file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); 
      sr = new System.IO.StreamReader(file); 
      string xmlString = sr.ReadToEnd(); 
      sr.Close(); 
      file.Close(); 
      return Deserialize(xmlString); 
     } 
     finally 
     { 
      if ((file != null)) 
      { 
       file.Dispose(); 
      } 
      if ((sr != null)) 
      { 
       sr.Dispose(); 
      } 
     } 
    } 
    #endregion 
} 

또 다른 파일 내 클래스 파일입니다

많은 답변을 stackoverflow 시도했지만 얻을 수 없습니다.

도움을 주셨습니다.

미리 감사드립니다.

답변

0

제 생각 엔 XML 시작시 인코딩 및/또는 BOM (Byte Order Mask) 때문입니다.

한 가지 문제는 XML 출력에 인코딩 정보가 누락되어 있다는 것입니다. 나는 그것이 UTF-8로 되돌아 간다고 생각한다.

동시에 .NET은 기본적으로 UTF-16 인코딩을 사용하고 스트림/파일에 쓰면 BOM이 추가됩니다. BOM은 XML 파서를 폭파시킵니다.

일부 HEX 편집기로 XML 파일을 확인하고 XML 시작 부분에 예기치 않은 보이지 않는 기호가 없는지 확인하십시오.

다음은 내가 사용한 샘플 XML 직렬화/비 직렬화 코드입니다. BOM이없는 UTF-8 인코딩을 사용하여 항상 XML 파일을 생성해야합니다. 또한 XML 헤더 앞에 BOM 또는 다른 정크가있는 경우에도 작동해야합니다.

public class XmlDataSerializer 
{ 
    public string Serialize<T>(T objectValue) where T : class 
    { 
     var utf8WithoutBom = new UTF8Encoding(false); 
     var xmlSerializer = new XmlSerializer(typeof(T)); 

     var xmlWriterSettings = new XmlWriterSettings 
     { 
      Indent = true, 
      Encoding = utf8WithoutBom 
     }; 

     using (var memoryStream = new MemoryStream()) 
     { 
      using (var writer = XmlWriter.Create(memoryStream, xmlWriterSettings)) 
      { 
       xmlSerializer.Serialize(writer, objectValue); 
       return utf8WithoutBom.GetString(memoryStream.ToArray()); 
      } 
     } 
    } 

    public T Deserialize<T>(string stringValue) where T : class 
    { 
     var xmlSerializer = new XmlSerializer(typeof(T)); 

     //hacky way to get rid of BOM for all encodings 
     var xmlStart = stringValue.IndexOf("<?xml", StringComparison.Ordinal); 
     if (xmlStart > 0) 
     { 
      stringValue = stringValue.Remove(0, xmlStart); 
     } 

     using (var stringReader = new StringReader(stringValue)) 
     { 
      using (var xmlReader = XmlReader.Create(stringReader)) 
      { 
       return xmlSerializer.Deserialize(xmlReader) as T; 
      } 
     } 
    } 
} 
+0

수동으로 XML 헤더 태그를 추가하려고 시도했지만 여전히 동일한 오류가 발생합니다. XML 문서 (1, 41)에 오류가 있습니다. ** 삭제되었습니다. ** xmlns = "---"** 이제 위의 오류가 오지는 않지만 변환 된 개체 속성에 XML 파일의 값이 없습니다. –

+0

, 약간의 조언을 부탁해주십시오. –

+0

샘플 코드를 추가했습니다. 모범 사례를 보여줄 필요는 없지만 시나리오에 따라 작동해야합니다. 코드는 기존 코드에 맞게 쉽게 조정할 수 있어야합니다. 또한 시간이 지남에 따라 직렬화가 개체에 구워지면 안되기 때문에 (예 : 일부 시점에서 JSON으로 전환하려는 경우 등) 엔티티 코드와 직렬화를 분리해야합니다. –

관련 문제