0

コンソールから入力された値から正しい値をリストするのに問題があります。私のXMLファイルは次のとおりです。

<Students>
  <Student>
    <Name>Name1</Name>
    <Surname>Surname1</Surname>
    <Index>2222</Index>
    <Subject name="History">
      <Class>Class2</Class>
      <Status status="passed">
        <Grade>A</Grade>
      </Status>
    </Subject>
  </Student>
  <Student>
    <Name>Name2</Name>
    <Surname>Surname2</Surname>
    <Index>3333</Index>
    <Subject name="Math">
      <Class>Class3</Class>
      <Status status="passed">
        <Grade>D</Grade>
      </Status>
    </Subject>
  </Student>
</Students>

私がやろうとしているのは、たとえば 3333 と入力すると、学生が所属するクラスを一覧表示したいということです。この場合は「Class3」です。私のコードは次のようなものです:

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load("Students.xml");

    Console.WriteLine("\nInsert Index Number");
    string result = Console.ReadLine();

    XmlNodeList xnList = xmlDoc.SelectNodes("//Student/Index");

    XmlNodeList xnList2 = xmlDoc.SelectNodes("//Student/Subject/Class");
    string result2 = null;
    for (int i = 0; i < xnList.Count; i++)
    {
        string nodeval = xnList[i].InnerText;
        if (nodeval == result)
        for (int j = 0; j < xnList2.Count; j++)
        {
                result2 = xnList2[j].InnerText;
                Console.WriteLine("Result" + result2);
        }
    }

}

何か助けはありますか?ありがとう

4

1 に答える 1

0

以下はあなたの答えです。これは基本的に、値が「3333」の親 Index ノードを持つすべての Class ノードが必要であることを示しています。一致を見つけるために、2 つのノード セットを使用してネストされた FOR ループを実行する必要はありません。

 /Students/Student//Class[../..//Index[.="3333"]]
 or
 /Students/Student//Class[../../Index[.="3333"]]
 or
 //Student//Class[../../Index[.="3333"]]

これは URL http://www.xpathtester.com/testでテストできます 。XPath テキスト ボックスに XPath 式を貼り付け、XML の大きなテキスト ボックスに XML を貼り付けて、[テスト] をクリックします。ボタン。

完全なソース コードが必要な場合は、以下を参照してください。重要なのは、正しい XPATH 式を作成し、「インデックス」と呼ばれるさまざまな値で文字列の置換/連結を行うことです。これにより、Index を呼び出したコマンド ラインから入力された値を持つすべてのクラス ノードが返されます。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("Students.xml");

            Console.WriteLine("\nInsert Index Number");
            string index = Console.ReadLine();

            //the critical piece is here, creating the correct xpath expression
            string xPathString = String.Format("/Students/Student//Class[../..//Index[.=\"{0}\"]]", index);

            XmlNodeList nodeList = xmlDoc.SelectNodes(xPathString);
            foreach (XmlNode node in nodeList)
            {
                Console.WriteLine("Index: {0} Class: {1}", index, node.InnerText);
            }
            Console.ReadLine();
        }
    }

}

于 2014-01-30T03:00:50.267 に答える