2017-12-28 82 views
0

xml値を読み込んでクラスのインスタンスを作成するこの関数があります。リフレクションを使用してXMLノードを読み取るC#

linqとリフレクションを組み合わせてクラスのプロパティを指定せずに、コード行を少なくしてクラスを作成する方法はありますか?

は、私が追加した場合、このメソッドを変更したりはtest_class

/// <summary> 
    /// Get the values of a xml node and return a class of type Class_Test 
    /// </summary> 
    /// <param name="sXmlFileName">Path to xml file.</param> 
    /// <param name="sNodeName">Name of node to get values.</param> 
    /// <returns>Class_Test New class with the values set from XML.</returns> 
    public static Class_Test Func_ReadXMLNode(string sXmlFileName, string sNodeName) 
    { 
     //Load XML 
     XDocument xml_Document; 
     Class_Test result; 
     try 
     { 
      xml_Document = XDocument.Load(sXmlFileName); 
      //Read XML Section 
      var xmlValues = from r in xml_Document.Descendants(sNodeName) 
          select new Class_Test 
          { 
           sNetworkInterfaceName = Convert.ToString(r.Element("").Value), 
           iNetworkInterfacePort = Convert.ToInt32(r.Element("").Value), 
           sCertificateFile = Convert.ToString(r.Element("").Value), 
           sCertificateName = Convert.ToString(r.Element("").Value), 
           iKeepAliveSendingTime = Convert.ToInt32(r.Element("").Value), 
           iMaximumTimeWithoutKeepAlive = Convert.ToInt32(r.Element("").Value), 
           sSqlServer = Convert.ToString(r.Element("").Value), 
           sDatabase = Convert.ToString(r.Element("").Value), 
           iFtpRetries = Convert.ToInt32(r.Element("").Value), 
           sDetectionFilesDirectory = Convert.ToString(r.Element("").Value), 
           sImgDirectory = Convert.ToString(r.Element("").Value), 
           sLocalDirectory = Convert.ToString(r.Element("").Value), 
           sOffenceDirectory = Convert.ToString(r.Element("").Value), 
           sTmpDirectory = Convert.ToString(r.Element("").Value) 
          }; 

      result = xmlValues.FirstOrDefault(); 

     } 
     catch (IOException Exception1) 
     { 
      LogHelper.Func_WriteEventInLogFile(DateTime.Now.ToLocalTime(), enum_EventTypes.Error, "Func_ReadXMLConfig()", "Source = " + Exception1.Source.Replace("'", "''") + ", Message = " + Exception1.Message.Replace("'", "''")); 
      result = new Class_Test(); 
     } 

     return result; 
    } 

にいくつかのフィールドを削除するには避けるようにしようとすると、これはClass_Textです:

/// <summary> 
/// Class of operation mode. 
/// </summary> 
public class Class_OperationMode 
{ 
    #region CONFIG_PARAMETERS 
    /// <summary> 
    /// Name of the network interface. 
    /// </summary> 
    public string sNetworkInterfaceName; 
    /// <summary> 
    /// Port of the network interface. 
    /// </summary> 
    public int iNetworkInterfacePort; 
    /// <summary> 
    /// Path to certificate file. 
    /// </summary> 
    public string sCertificateFile; 
    /// <summary> 
    /// Name of the certificate. 
    /// </summary> 
    public string sCertificateName; 
    /// <summary> 
    /// Time to keep alive the connection while sending data. 
    /// </summary> 
    public int iKeepAliveSendingTime; 
    /// <summary> 
    /// Time before timeout of the connection. 
    /// </summary> 
    public int iMaximumTimeWithoutKeepAlive; 
    /// <summary> 
    /// Database server instance. 
    /// </summary> 
    public string sSqlServer; 
    /// <summary> 
    /// Path to .mdf file of database. 
    /// </summary> 
    public string sDatabase; 
    /// <summary> 
    /// Max retries to try to connect to FTP Server. 
    /// </summary> 
    public int iFtpRetries; 
    /// <summary> 
    /// Path to detections files directory. 
    /// </summary> 
    public string sDetectionFilesDirectory; 
    /// <summary> 
    /// Path to images directory. 
    /// </summary> 
    public string sImgDirectory; 
    /// <summary> 
    /// Path to local directory. 
    /// </summary> 
    public string sLocalDirectory; 
    /// <summary> 
    /// Path to folder where save and retrieve offences. 
    /// </summary> 
    public string sOffenceDirectory; 
    /// <summary> 
    /// Path to temp directory. 
    /// </summary> 
    public string sTmpDirectory; 

    #endregion 

UPDATE:コメントのおかげで、私は更新しますコード:

public static Class_Test Func_ReadXMLNode(string sXmlFileName, string sNodeName){ 
//Load XML 
XDocument xml_Document; 
Class_Test result; 
try 
{ 
    xml_Document = XDocument.Load(sXmlFileName); 
    //Read XML Section 

    //Get xml values of descendants 
    XElement xmlValues = xml_Document.Descendants(sNodeName).FirstOrDefault(); 
    //Create serializer 
    XmlSerializer serializer = new XmlSerializer(typeof(Class_Test)); 

    //Deserialize 
    using (XmlReader reader = xmlValues.CreateReader()) 
    { 
     result = (Class_Test)serializer.Deserialize(reader); 
    } 

} 
catch (IOException Exception1) 
{ 
    LogHelper.Func_WriteEventInLogFile(DateTime.Now.ToLocalTime(), enum_EventTypes.Error, "Func_ReadXMLConfig()", "Source = " + Exception1.Source.Replace("'", "''") + ", Message = " + Exception1.Message.Replace("'", "''")); 
    result = new Class_Test(); 
} 

return result; 
} 

ありがとうございます。敬具、

ホアキン

+1

から

XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem)); // A FileStream is needed to read the XML document. FileStream fs = new FileStream(filename, FileMode.Open); XmlReader reader = XmlReader.Create(fs); // Declare an object variable of the type to be deserialized. OrderedItem i; // Use the Deserialize method to restore the object's state. i = (OrderedItem)serializer.Deserialize(reader); fs.Close(); 

?とにかく既にすべてがメモリにロードされています。 https://msdn.microsoft.com/en-us/library/tz8csy73%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 – KSib

答えて

0

私は何youreのを探していることはシリアライズ/デシリアライゼーションのだと思います。 XMLシリアライゼーションを処理するための.netで役に立つものがたくさんあります。私はこの例をドキュメント(下のリンク)から盗んだ。あなただけのクラスに全体をデシリアライズされていないのはなぜhttps://msdn.microsoft.com/en-us/library/tz8csy73(v=vs.110).aspx

関連する問題