ラベル C# の投稿を表示しています。 すべての投稿を表示
ラベル C# の投稿を表示しています。 すべての投稿を表示

2008年1月18日金曜日

[C#]XMLの読み込み 書き込み

とあることをやるためにDBを使わずXMLを使うことになったのでとりあえず書き残します。

始めにXmlを操作するので宣言をしておく
ついでにパスを取得したりもするのでIOの宣言もしておく
using System.Xml;
using System.IO;

public class XmlIo
{
XmlDocument doc = new XmlDocument();
//絶対パスを取得しファイルを指定する
string xmlPath = System.IO.Directory.GetCurrentDirectory();
string xmlFile = "data.xml";
#region XML読み込み
public void ReadXml(string nodes)
{
XmlDocument doc = new XmlDocument();
doc.Load(xmlFile);
//リストに引数を渡す
XmlNodeList list = doc.SelectNodes(nodes);
#if DEBUG
foreach (XmlNode node in list)
{
System.Diagnostics.Debug.Write(node.InnerText + "\n");
}
#endif
}
#endregion
#region XML書き込み
public void SaveXml()
{
XmlDocument doc = new System.Xml.XmlDocument();
var estate = doc.CreateElement("estate");
var name = doc.CreateElement("name");
name.AppendChild(doc.CreateTextNode("○○"));
estate.AppendChild(name);
var terop = doc.CreateElement("terop");
terop.AppendChild(doc.CreateTextNode("XMLの書き込み"));
estate.AppendChild(terop);
var items = doc.CreateElement("items");
estate.AppendChild(items);
doc.AppendChild(estate);
//デバッグ時はXmlを上書きされないようにする
#if DEBUG
string debugXml = xmlPath + "/../xml" + xmlFile;
var writer = new System.Xml.XmlTextWriter(debugXml, Encoding.UTF8);
#else
var writer = new System.Xml.XmlTextWriter(xmlPath + xmlFile, Encoding.UTF8);
#endif
writer.WriteStartDocument();
writer.Formatting = System.Xml.Formatting.Indented;
doc.WriteTo(writer);
writer.Close();
}
#endregion
}

XmlDocumentを使ってやりとりを行っています。
ReadXml()では引数にXMLのタグ(?)を書くようにします。

リストに引数が渡り、その部分のデータを取得してます。
#if DEBUGの部分ではデバッグ時に確認のため出力ウィンドウに取得したデータを表示させるようにしてます。

SaveXml()に引数はないです。

現在未完成なので説明とかも簡略化します。
varは、intやchar等のいろんな型に対応しています。
しかしローカル変数としか使えません。

CreateElementで始め、AppendChildで終わらせる。







とイメージしてもらえれば幸いです。


#ifDEBUGではデバッグ中に書き出すファイルが上書きされると困る場合お使いください。




新年ですね。

昨年は3ヶ月もしないうちにいろんな人に見てもらえ、驚いてます。

しかしながらあまり書く時間と気力がないのでのっそのっそとやってます。

今年もかけるときがあったら書こうと思います。

2007年11月17日土曜日

[C#]時間数値化、数値時間化、月末日付をまとめたC#用クラス

public class Common
{
CSScript cs = new CSScript();

//*** strTimeに入っている値を数値(分)に変換して返します。 ***
// strTime : 計算対象の時間。必ずhh:mm形式で入力するようにしてください。
// 変換できないときは0を返します。
public int 時間_数値化(string strTime)
{
  int wkHour;
  int wkMinute;
  if( strTime == null)
  {
   return 0;
  }
  //時間を取得
  wkHour = (int)CSScript.Val(CSScript.Left(strTime, strTime.IndexOf(":", 1) - 1));
  wkMinute = (int)CSScript.Val(CSScript.Right(strTime, 2));
  try{
   return wkHour * 60 + wkMinute;
  }catch(Exception){
   return 0;
  }
}
//*** ↑の処理で数値化された時間を元に戻します。変換失敗時は空文字列を返します ***
public string 数値_時間化(int lngTime)
{
  if(lngTime == 0)
  {
   return "";
  }
  try
  {
   return CSScript.Fix(lngTime / 60, 0) + ":" + string.Format( "00", lngTime % 60);
  }catch(Exception){
   return "";
  }
}
//*** 月末日付を取得します ***
// 変換できなかった場合は0を返します。
public int 月末日付(string strMonth)
{
  DateTime dt =DateTime.Now;
  return DateTime.DaysInMonth(dt.Year, (int)CSScript.Val(strMonth));
}



VBで作ったのをC#にする際に、勢いのままクラスも直していたのでついでなので乗せておきます。

ってかなんかインデントがおかしい

[C#]文字列操作関係クラス

public class CSScript
{
  #region "IsNull"
  //空白判定(戻り値:True=空白, False=空白では無い)
  public bool IsNull(string text)
  {
    //空文字判定
    if( text == null)
    {
      return true;
    }
    //""文字判定
    if( text == "")
    {
      return true;
    }
    return false;
  }
  #endregion

  #region"NZf"
  //空文字を変換
  public int NZf(string a)
  {
    if(IsNull(a) == true )
    {
      return 00;
    }
    else
    {
      return (int)Val(a);
    }
  }
  #endregion

  #region Left メソッド
  /// -----------------------------------------------------------------------------------
  ///


  /// 文字列の左端から指定された文字数分の文字列を返します。

  ///
  /// 取り出す元になる文字列。
  ///
  /// 取り出す文字数。
  ///
  /// 左端から指定された文字数分の文字列。
  /// 文字数を超えた場合は、文字列全体が返されます。

  /// -----------------------------------------------------------------------------------
  public static string Left(string stTarget, int iLength)
  {
    if (iLength <= stTarget.Length)     {       return stTarget.Substring(0, iLength);     }     return stTarget;   }   #endregion   #region Mid メソッド (+1)   /// -----------------------------------------------------------------------------------   ///
  /// 文字列の指定された位置以降のすべての文字列を返します。

  ///
  /// 取り出す元になる文字列。
  ///
  /// 取り出しを開始する位置。
  ///
  /// 指定された位置以降のすべての文字列。

  /// -----------------------------------------------------------------------------------
  public static string Mid(string stTarget, int iStart)
  {
    if (iStart <= stTarget.Length)     {       return stTarget.Substring(iStart - 1);     }     return string.Empty;   }   /// -----------------------------------------------------------------------------------   ///
  /// 文字列の指定された位置から、指定された文字数分の文字列を返します。

  ///
  /// 取り出す元になる文字列。
  ///
  /// 取り出しを開始する位置。
  ///
  /// 取り出す文字数。
  ///
  /// 指定された位置から指定された文字数分の文字列。
  /// 文字数を超えた場合は、指定された位置からすべての文字列が返されます。

  /// -----------------------------------------------------------------------------------
  public static string Mid(string stTarget, int iStart, int iLength)
  {
    if (iStart <= stTarget.Length)     {       if (iStart + iLength - 1 <= stTarget.Length)       {         return stTarget.Substring(iStart - 1, iLength);       }       return stTarget.Substring(iStart - 1);     }     return string.Empty;   }   #endregion   #region Right メソッド (+1)   /// -----------------------------------------------------------------------------------   ///
  /// 文字列の右端から指定された文字数分の文字列を返します。

  ///
  /// 取り出す元になる文字列。
  ///
  /// 取り出す文字数。
  ///
  /// 右端から指定された文字数分の文字列。
  /// 文字数を超えた場合は、文字列全体が返されます。

  /// -----------------------------------------------------------------------------------
  public static string Right(string stTarget, int iLength)
  {
    if (iLength <= stTarget.Length)     {       return stTarget.Substring(stTarget.Length - iLength);     }     return stTarget;   }   #endregion   #region Val メソッド (+2)   /// -----------------------------------------------------------------------------   ///
  /// 指定した文字列に含まれる数値を変換して返します。

  ///
  /// 任意の有効な文字列。
  ///
  /// 指定した文字列に含まれる数値。

  /// -----------------------------------------------------------------------------
  public static double Val(string stTarget)
  {
    // Null 値の場合は 0 を返す
    if (stTarget == null)
    {
      return 0;
    }

    int iCurrent = 0;
    int iLength = stTarget.Length;

    // 評価対象外の文字をスキップする
    for (iCurrent = 0; iCurrent < chone =" stTarget[iCurrent];">= iLength)
    {
      return 0;
    }

    bool bMinus = false;

    // 先頭にある符号を判定する
    switch (stTarget[iCurrent])
    {
      case '-':
        bMinus = true;
        iCurrent++;
        break;
      case '+':
        iCurrent++;
        break;
    }

    int iValidLength = 0;
    int iPriod = 0;

    double dReturn = 0D;

    bool bDecimal = false;
    bool bShisuMark = false;

    // 1 文字ずつ有効な文字かどうか判定する
    while (iCurrent < chcurrent =" stTarget[iCurrent];" chcurrent ="="" chcurrent ="="" chcurrent ="="" chcurrent ="="" chcurrent ="="" chcurrent ="="" dreturn =" (dReturn">= '1') && (chCurrent <= '9'))       {         iCurrent++;         iValidLength++;         dReturn = (dReturn * 10) + double.Parse(chCurrent.ToString());       }       else if (chCurrent == '.')       {         iCurrent++;         if (bDecimal)         {           break;         }         bDecimal = true;         iPriod = iValidLength;       }       else if ((chCurrent == 'e') (chCurrent == 'E') (chCurrent == 'd') (chCurrent == 'D'))       {         bShisuMark = true;         iCurrent++;         break;       }       else       {         break;       }     }     int iDecimal = 0;     // 小数点が判定された場合     if (bDecimal)     {       iDecimal = iValidLength - iPriod;     }     // 指数が判定された場合     if (bShisuMark)     {       bool bShisuValid = false;       bool bShisuMinus = false;       double dCoef = 0D;       // 指数を検証する       while (iCurrent < chcurrent =" stTarget[iCurrent];" chcurrent ="="" chcurrent ="="" chcurrent ="="" chcurrent ="="" chcurrent ="="">= '0') && (chCurrent <= '9'))         {           dCoef = (dCoef * 10) + double.Parse(chCurrent.ToString());           iCurrent++;         }         else if (chCurrent == '+')         {           iCurrent++;         }         else if ((chCurrent != '-') bShisuValid)         {           break;         }         else         {           bShisuValid = true;           bShisuMinus = true;           iCurrent++;         }       }       // 指数の符号に応じて累乗する       if (bShisuMinus)       {         dCoef += iDecimal;         dReturn *= System.Math.Pow(10, - dCoef);       }       else       {         dCoef -= iDecimal;         dReturn *= System.Math.Pow(10, dCoef);       }     }     else if (bDecimal && (iDecimal != 0))     {       dReturn /= System.Math.Pow(10, iDecimal);     }     // 無限大の場合は 0 を返す     if (double.IsInfinity(dReturn))     {       return 0;     }     // マイナス判定の場合はマイナスで返す     if (bMinus)     {       return -dReturn;     }     return dReturn;   }   /// -----------------------------------------------------------------------------   ///
  /// 指定した文字に含まれる数値を変換して返します。

  ///
  /// 任意の有効な文字。
  ///
  /// 指定した文字に含まれる数値。

  /// -----------------------------------------------------------------------------
  public static int Val(char chTarget)
  {
    return (int)Val(chTarget.ToString());
  }

  /// -----------------------------------------------------------------------------
  ///
  /// 指定したオブジェクトに含まれる数値を変換して返します。

  ///
  /// 任意の有効なオブジェクト。
  ///
  /// 指定したオブジェクトに含まれる数値。

  /// -----------------------------------------------------------------------------
  public static double Val(object oTarget)
  {
    if (oTarget != null)
    {
      return Val(oTarget.ToString());
    }

    return 0D;
  }

  #endregion

  #region Fix

  /// ------------------------------------------------------------------------
  ///
  /// 指定した精度の数値に切り捨てします。

  ///
  /// 丸め対象の倍精度浮動小数点数。
  ///
  /// 戻り値の有効桁数の精度。
  ///
  /// iDigits に等しい精度の数値に切り捨てられた数値。

  /// ------------------------------------------------------------------------
  public static double Fix(double dValue, int iDigits)
  {
    double dCoef = System.Math.Pow(10, iDigits);

    return dValue > 0 ? System.Math.Floor (dValue * dCoef) / dCoef:
      System.Math.Ceiling(dValue * dCoef) / dCoef;
  }

  #endregion
}


C#です。はいC#ですよ。
お前出来んのかよ!とか聞かないでください。
VBのフォーム制御をCやJavaで書いてるって感覚だけでやってるんですから。
さて雑談はこれくらいにしておいて。
文字列操作です。
VB6にある関数や、先にも書いた関数があります。
まぁ半分コピーですけどね。
VB6にある関数は結構便利だったりします。
C#にあるかもしれないけど、言語が変わっても大丈夫だと思えるようにしたいのでこれを作ってみました。