2012-05-04 33 views
2

これはスクリプトですが、コンソールにはスペースのみが表示されます。誰かがxPathを使用してXMLファイルから属性値を取得する方法を説明できますか?私は推測XPathを使用してXMLノードの属性値を取得する方法

XPathNavigator nav; 
    XPathDocument docNav; 
    XPathNodeIterator NodeIter; 
    XmlNamespaceManager ns; 

    Int32 elementCount; 

    String windowName; 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     docNav = new XPathDocument("C:/BlueEyeMacro/DaMaGeX/Applications/WindowBuilder/GUI.xml"); 
     nav = docNav.CreateNavigator(); 
     ns = new XmlNamespaceManager(nav.NameTable); 
     elementCount = nav.Select("/GUI/window").Count; 
     Console.WriteLine(elementCount); 
     for (int i = 1; i <= elementCount; i++) 
     { 
      NodeIter = nav.Select("/GUI/window[@ID="+i+"]"); 
      windowName = NodeIter.Current.GetAttribute("name", ns.DefaultNamespace); 
      Console.WriteLine("{0}", windowName); 
     } 
    } 
} 

XMLファイル
<GUI>
<window ID="1" name="mainWindow" parent="0" type="0" text="My first window" options="Option 1;" actions="action 1;" exit="exit;" />
<window ID="2" name="secondWindow" parent="0" type="0" text="My second window" options="Option 1;" actions="action 1;" exit="exit;" />
<window ID="3" name="thirdWindow" parent="0" type="0" text="My third window" options="Option 1;" actions="action 1;" exit="exit;" />
</GUI>

+0

次のコードは奇妙に見えます。あなたはどんな問題があるか説明してください。 –

+0

DaMaGeX:現在受け入れているソリューションよりも短く/簡単なソリューションに興味があるかもしれません。 –

答えて

3

は、あなたが最初にこのコードのようにNodeIter.MoveNext()を呼び出す必要があり:

XPathNodeIterator nodesText = nodesNavigator.SelectDescendants(XPathNodeType.Text, false); 

while (nodesText.MoveNext()) 
{ 
    Console.Write(nodesText.Current.Name); 
    Console.WriteLine(nodesText.Current.Value); 
} 
+0

ありがとう、ちょうどそのトリックでした! – DaMaGeX

0

ます。また、これを実行するようにコードを変更することができます。

for (int i = 1; i <= elementCount; i++) 
    { 
     var NodeIter = nav.SelectSingleNode("/GUI/window[@ID='"+i+"']/@name"); //This selects the @name attribute directly 
     Console.WriteLine("{0}", NodeIter.Value); 
    } 

あなたは一意のIDによってノードを識別している考えると、SELECTSINGLENODEはあなたがやろうとしているもののためのより良いフィット感です。

1

あなたは直接属性の文字列値を取得することができます:それはそうなのWinFormプロジェクトでコンソール出力を使用していますが、そうでない場合はSelect文が合理的であるよう

for (int i = 1; i <= elementCount; i++) 
    { 
    // This obtains the value of the @name attribute directly 
    string val = 
       nav.Evaluate("string(/GUI/window[@ID='"+i+"']/@name)") as string;     
    Console.WriteLine(val); 
    } 
関連する問題