C#の定数用クラスについて

このQ&Aのポイント
  • C#の定数用クラスについて定数用のクラスを宣言し、定数を取得してxmlファイルからノードが読み込めません。
  • 定数用クラスを使ってxmlファイルからノードを読み込む際に、一部のコードで値が取得できず、nullになってしまいます。
  • 定数用クラスとxmlファイルの組み合わせで値を取得する際に問題が発生しています。
回答を見る
  • ベストアンサー

C#の定数用クラスについて

定数用のクラスを宣言し、定数を取得してxmlファイルからノードが読み込めません。 xmlファイル(set.xml) <?xml version="1.0" encoding="utf-8"?> <Setting> <!--メインフォーム--> <mainForm> <Width>400</Width> </mainForm> </Setting> 定数用クラス(nsConst.cs) namespace nsConst{ class setttingConst{ public readonly string FORM_NAME = "mainForm"; public readonly string TD_WIDTH = "Width"; } xml用クラス(nsxmlReWriter.cs) namespace nsxmlReWriter{ class xmlReWriter { public String read(String element1, String element2) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(@"c:\\test\set.xml"); string ret = null; try { //Rootの取得 XmlElement Root = xml.DocumentElement; //子ノードの取得 XmlNodeList child = Root.GetElementsByTagName(element1); //該当ありの場合 if (child.Count > 0) { XmlElement gchild = (XmlElement)child.Item(0); if (gchild.GetElementsByTagName(element2).Count > 0) { ret = gchild.GetElementsByTagName(element2).Item(0).InnerText; } } } catch (Exception ex) { throw new Exception(ex.Message); } return ret; } } //ここから定数、xmlクラスを呼び出す。 MainLogic.cs namespace nsMainLogic{ class MainLogic{ private void init(){ public readonly string FORM_NAME1 = "mainForm"; public readonly string TD_WIDTH1 = "Width"; setttingConst con = new setttingConst(); xmlReWriter xmlRw = new xmlReWriter(); string width1 = xmlRw.read(con.FORM_NAME,con.TD_WIDTH); //(1) string width2 = xmlRw.read(FORM_NAME1,TD_WIDTH1); //(2) : 省略 : } } } (1)ではxmlファイルを読み込んだ結果がnullなってしまい値が取れません。 (2)では値がとれます。 わかりましたらよろしくお願いします。

質問者が選んだベストアンサー

  • ベストアンサー
  • yotchan2
  • ベストアンサー率61% (8/13)
回答No.2

補足ありがとうございます。 >Eclipseみたいに複数フィールドに対してGetterSetter >って作れるんでしょうか? 作れないかと思います。私も以前Eclipseを使用していて、VisualStudio環境に移ったのですが、あれは便利でしたね。 プロパティのように使いたいということなので、こういうのはどうでしょうか? public abstract class setttingConst {   public const string FORM_NAME = "mainForm";   public const string TD_WIDTH = "Width"; } 抽象クラスなので実体化する必要がなく、constを使用することでプロパティのように使用することが可能です。

nirusu
質問者

お礼

お礼が遅くなってすいませんでした。 結果的には、XMLの書き方がおかしかったみたいでした。 抽象クラスはあまり良くわからなかったので勉強になりました。 ありがとうございました。

その他の回答 (1)

  • yotchan2
  • ベストアンサー率61% (8/13)
回答No.1

コードを省略しすぎて情報が少なすぎです。 setttingConstクラスに至っては、コンストラクタも無いので、ビルドすら通らない記述になってしまっています。 デバッグ実行が可能であれば、(1)の時にちゃんと引数が渡っているか確認してみるとよいかと思います。 要点をまとめて、補足願います。

nirusu
質問者

補足

回答ありがとうございます。 デバッグで値を確認したんですが、きちんと取れています。 何がしたいのかと言いますと、プロパティのように使いたいんです。 定数なので値を変える必要がないので、setterを書くのがいやなだけです。なぜかxmlReWriterクラスだけ正しく動きません。VS2005を使っているんですが、Eclipseみたいに複数フィールドに対してGetterSetter って作れるんでしょうか?フィールドのカプセル化から作れるのは知っているんですが、あれって一個ずつしか作れないんですよね?

関連するQ&A

  • C#のXmlDocumentについて

    C#のXmlDocumentについて質問です。 using System; using System.Xml; using System.Windows; public class XmlNewClass{ public static void Main(String [] args){ XmlDocument xmlObj = new XmlDocument(); xmlObj.Load("./test.xml"); XmlNode nodeObj = xmlObj.GetElementsByTagName("root").Item(0); Console.WriteLine(nodeObj); } } 上記のようなコードがあったとします。 この場合、プロンプトに表示されるないようは 〔System.Xml.XmlElement〕という記述が出力されます。 次に XmlElement elementObj =nodeObj; というコードを追加したとします。 それを実行してみると /****************************************************************** xml.cs(21,26): error CS0266: 型 'System.Xml.XmlNode' を 'System.Xml.XmlElement' に暗黙的に変換できません。明示的な変換が存在します。(cast が不足していないかどうかを確認してください) ***************************************************************************/ というようなエラーがプロンプト上に表示されます。 これはnodeObjがXmlNodeというクラスだということですが (実際GetElementsByTagNameで帰って来るオブジェクトはXmlNodeというクラスだとマニュアルにも記載がありました) なぜ冒頭のコードで Console.WriteLine(nodeObj); の箇所の出力で〔XmlElement〕という内容が出力されたのでしょうか? 同じオブジェクトなのに、なぜ出力と型がことなるのでしょうか? ご教授よろしくお願いします。

  • JavaScriptでIEの自動ログインについて

    JavaScriptの初心者でIE上で表示されたログインボタンをクリックしたいのですが、name="ボタン名"がなくクリックできないんです。 「ie.document.MainForm(0).submit.click();」と記入してみたのですが、クリックできないんです。 下記のようなボタンをJavaScriptで押すにはどうしたらいいのでしょうか? どなたかすいませんがご教授ください。 ===================================================== ボタンのHTML <form name="MainForm" method="POST" action="/login" target="_self"> <table border="0" width="510"> <tr> <td width="140">&nbsp;</td> <td width="160" align="center"><input type="submit" style="width:100" value="ログイン" onClick="return buttonHandler('ok');"></td> <td width="210">&nbsp;</td> </tr> </table> <br> </form>

  • C#の配列の定数

    BCCを使用していたのですが、最近VS2013でC#を勉強し始めました フォームの指定した位置にいくつかのボタンを設置し、あらかじめ定義しておいた テーブルからボタンのtextを表示したいと思い、以下のようにコーディングしたのですが エラーが出てしまい思ったような結果に持って行くことができません C#ならこうした方がいいという指摘も含めて どうやるのがいいのか ご教授ください 足りない情報があれば追加します ちなみにまだテスト段階だから2列定義して1列しか表示するようにしかなってません ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace haneda { public partial class Form1 : Form { private Button[] buttons; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { int i; //ボタンコントロール配列の作成 this.buttons = new Button[table.MAX_R]; for (i = 0; i < buttons.Length; i++) { //ボタンコントロールのインスタンス作成 this.buttons[i] = new Button(); //プロパティ設定 this.buttons[i].Name = "btn" + i.ToString(); this.buttons[i].Text = table.roomNo[1, i]; <=ここがエラー this.buttons[i].Top = table.roomX01[i]; <=ここがエラー this.buttons[i].Left = table.roomY01[i]; <=ここがエラー this.buttons[i].Click += new System.EventHandler(button_Click); //コントロールをフォームに追加 this.Controls.Add(this.buttons[i]); } } private void button_Click(object sender, System.EventArgs e) { Button btn = (Button)sender; MessageBox.Show(btn.Name); } } public class define { public const bool IGNORE = false; //非表示 public const bool EFFECT = true; //表示 /* 最大値 */ public const int MAX_F = 2; //フロア数 public const int MAX_R = 3; //ルーム数 } public class table { /* ナンバー */ public readonly string[,] roomNo = new string[define.MAX_F, define.MAX_R] { { "101", "102", "103"}, { "201", "202", "203"} } /* 表示・非表示 */ public readonly bool[,] effectRoom = new bool[define.MAX_F, define.MAX_R] { {EFFECT, IGNORE, EFFECT}, {EFFECT, EFFECT, EFFECT} } public readonly int[] roomX01 = new int[define.MAX_R] { 5, 70, 135 } public readonly int[] roomY01 = new int[define.MAX_R] { 100, 100, 100 } } }

  • JListに一覧にして表示

    データベースから取得した結果を JListに一覧にして表示させたいのですが、 list.setText(table);の部分の setTextメソッドでシンボルが見つけられないと エラーが出てしまいます。 JListにsetTextを使っているからなのだと思いますが、 APIを探したのですがなかなかわかりません どう対処したらよいでしょうか?? private Connection connect() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost/???"; String user = "root"; String pass = ""; Connection con = DriverManager.getConnection(url,user,pass); return con; } Bookmark(){ JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab("表示", createPanel1()); } private JPanel createPanel1(){ JPanel p = new JPanel(); JList list = new JList(); JScrollPane scrollPane = new JScrollPane(); scrollPane.getViewport().setView(list); scrollPane.setPreferredSize(new Dimension(480, 340)); p.add(scrollPane); try{ //DBに接続 Connection con = connect(); //SQL発行先ほど指定したConnection con を利用 Statement stmt = con.createStatement(); String sql ="select * from Browser"; ResultSet rs = stmt.executeQuery(sql); //結果の取得 while(rs.next()){ String name = rs.getString("name"); String address = rs.getString("address"); String table = "<html><table>" + "<td>" + name + "</td>"+ "<td>"+ address +"</td>"+ "</table></html>"; list.setText(table); } //切断 con.close(); } catch(Exception ex) { System.out.println(ex);

    • ベストアンサー
    • Java
  • ブラウザ情報の件で困ってます・・・。

    ブラウザとバージョンによって、使用を制限したいのですが、ブラウザがNetscapeだと .disabled が使用できないみたいなのですが。 今ブラウザ情報の取得も以下のとおりかなり間に合わせ的なもので、もっといいやり方を教えていただけるとうれしいのですが、ちょっと急いでおりますのでご返答のほうよろしくお願い致します。 <!-- ブラウザ情報 document.write('<center><TABLE border="1" align="center">'); document.write("<TD></TD>あなたのブラウザ情報です</TR>"); document.write("<TR><TD>ブラウザ名は</TD><TD>"+navigator.appName+"</TD></TR>"); document.write("<TR><TD>バージョンは</TD><TD>"+navigator.appVersion+"</TD></TR>"); document.write("</TABLE>"); // ブラウザ情報 --> function GetVer(nvName, nvVer){ var Name; Name = new String(nvName); if(eval(Name) != "Microsoft Internet Explorer"){ mainForm.KAI_ACCT.disabled = true; mainForm.KAI_PASS.disabled = true; alert("このブラウザには対応していません。IE 5.0以上で使用してください。"); return false; }else{ var Version; Version = new String(nvVer); eval(Version.charAt(22)); if( eval(Version.charAt(22)) < 5 ){ mainForm.KAI_ACCT.disabled = true; mainForm.KAI_PASS.disabled = true; alert("このブラウザには対応していません。IE 5.0以上で使用してください。"); return false; }else{ return true; } } }

  • java strutsでの一覧表の表示方法について

    以下の内容でロジックを組んだのですが、 jspより表示される一覧表は、003 name3が3件表示されてしまいます。 一覧表を正しく表示できない原因を教えてください。 SP0010_FORM_Bean.java public class SP0010_FORM_Bean { protected String id; protected String name; public void setId(String s) { id = s; } public String getId() { return id; } public void setName(String s) { name = s; } public String getName() { return name; } } SP0010_FORM.java public class SP0010_FORM extends ValidatorForm{ protected List<SP0010_FORM_Bean> loopList; public void setLoopList(List<SP0010_FORM_Bean> list) { loopList = list; } public List<SP0010_FORM_Bean> getLoopList() { return loopList; } } SP0010_ACTION_10.java SP0010_FORM initBean = new SP0010_FORM(); request.setAttribute("list_form", initBean); List<SP0010_FORM_Bean> list = new ArrayList<SP0010_FORM_Bean>(); SP0010_FORM_Bean bean1 = new SP0010_FORM_Bean(); bean1.setId("001"); bean1.setName("name1"); list.add(bean1); bean1.setId("002"); bean1.setName("name2"); list.add(bean1); bean1.setId("003"); bean1.setName("name3"); list.add(bean1); initBean.setLoopList(list); jsp <table border="1"> <logic:iterate id="loop" name="list_form" property="loopList"> <tr> <td><bean:write name="loop" property="id" /></td> <td><bean:write name="loop" property="name" /></td> </tr> </logic:iterate> </table>

    • ベストアンサー
    • Java
  • フォームを閉じる方法

    VC#2008ExpressEditionを使用して仕事で使う在庫管理ソフトを作成しています。 まず、ウェルカムページが開いて、その後認証ページが開くように作っていますが、認証ページが開いたのと同時にウェルカムページを閉じたいのですが、閉じることが出来ません。どなたか教えて下さい。 ウェルカムページのコーディング using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace zaiko { public partial class welcomeForm : Form { public welcomeForm() { InitializeComponent(); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Form mainForm = new mainForm(); mainForm.Show(); } } } 認証ページのコーディング using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace zaiko { public partial class mainForm : Form { public mainForm() { InitializeComponent(); } private void mainForm_Load(object sender, EventArgs e) { Form welcomeForm = new Form(); welcomeForm.Close(); } } }

  • C# 引数の渡し方について

    C# 引数の渡し方について //Form1 private void loginbutton_Click(object sender, EventArgs e) { book[] bk = new book[100]; Form2 f = new Form2(bk[0]); f.ShowDialog(this); //モーダルフォーム } public class book { public string name; public int price; } //Form2 public Form2(WindowsFormsApplication1.Form1.book bk) { InitializeComponent(); } Form2にbkの配列のすべてを渡したいのですが今のソースだとbk[0]しかわたせていないようです どうすればbk[0]~bk[99]のすべてを渡せるのでしょうか

  • JavaScriptを使った計算フォーム

    JavaScriptを使った計算フォームで質問です。 人数をテキストボックスに入力し、そのあと項目を選ぶと計算がされるようにしたいのですが ラジオボタンが持っているvalueを取り出せません。 下記の「←------???」と書いてあるところを何とかすれば完成だと思うのですが、 どなたか教えていただけないでしょうか? <script language="JavaScript" type="text/JavaScript"> function sjLeft(source,length) { if (source.length < length) { return (""); } return source.substr(0, length); } function sjReplace(source,start,length,target) { sjlen = source.length; if ((start > sjlen) || (start < 0)) { return String(""); } return String(sjLeft(source,start ) + target + source.substr(start+length, sjlen)); } function sjInsert( source, start, target) { return sjReplace(source,start,0,target); } function fcheck(obj) { s1_2value = ??? * new Number(document.form1.n1.value); ←------??? document.form1.s1_2.value = String(s1_2value); document.form1.total.value = s1_2value; return true; } </script> <form name="form1" method="POST"> <table width="400" border="1"> <tr> <td>人数</td> <td></td> <td><input type=text name=n1 size=8 onChange="fcheck(this);">人</td> <td></td> </tr> <tr> td><input name="n2" type="radio" value="13000" onChange="fcheck(this);">食事A</td> <td>\13,000</td> <td>×人数</td> <td><input name=s1_2 type=text size=8 readonly>円</td> </tr> <tr> <td colspan="2">&nbsp;</td> <td>総計</td> <td><input type=text readonly name=total size=10>円</td> </tr> </table> </form>

  • Xercesを使ったjavaでのXML解析

    DOMを使ってXML文書を解析するJavaのソースコードで、DOMパーサは、クラス org.apache.xerces.parsers.DOMParserで参照している下記のプログラムで、 [Fatal Error] :17:109: The entity name must immediately follow the '&' in the entity reference. org.xml.sax.SAXParseException; lineNumber: 17; columnNumber: 109; The entity name must immediately follow the '&' in the entity reference. のエラーが出てしまって、解決策が分かりかねています。Javaのネットワークプログラミングに詳しい方、御教示願えればと思います。 package nikkei; import java.io.ByteArrayInputStream; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class TwitterSearch { public static void main(String[] args) throws Exception { TwitterSearch search = new TwitterSearch(); search.search("日経ソフトウエア"); } public void search(String keyword) throws Exception { SearchAPIClient client = new SearchAPIClient(); String xml = client.execute(keyword); parse(xml); } private void parse(String xml) throws Exception { DOMParser parser = new DOMParser(); try { parser.parse(new InputSource(new ByteArrayInputStream(xml.getBytes()))); Document doc = parser.getDocument(); NodeList entries = doc.getElementsByTagName("entry"); for (int i = 0; i < entries.getLength(); i++) { String name = null; String tweet = null; Element entry = (Element) entries.item(i); NodeList titleList = entry.getElementsByTagName("title"); if (titleList.getLength() == 1) { tweet = titleList.item(0).getTextContent(); } NodeList authorList = entry.getElementsByTagName("author"); if (authorList.getLength() == 1) { Element author = (Element) authorList.item(0); NodeList nameList = author.getElementsByTagName("name"); if (nameList.getLength() == 1) { name = nameList.item(0).getTextContent(); } } System.out.println(name + "さんのツイート"); System.out.println("\t" + tweet); } } catch (Exception e) { e.printStackTrace(); } } } package nikkei; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class SearchAPIClient { public String execute(String keyword) throws Exception { String url = "https://twitter.com/search?q=" + keyword; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } else { return null; } } } よろしくお願いいたします。

    • ベストアンサー
    • Java

専門家に質問してみよう