1

私はC#に慣れていません。xml ドキュメントを解析し、子ノードの特定のノードをカウントする必要があります。

例えば:

<Root>
   <Id/>
   <EmployeeList>
      <Employee>
         <Id/>
         <EmpName/>
      </Employee>
      <Employee>
         <Id/>
         <EmpName/>
      </Employee>
      <Employee>
         <Id/>
         <EmpName/>
      </Employee>
    </EmployeeList>
</Root>

このxmlでは、「従業員」ノードをどのように数えますか??

C#でXmlDocumentクラスを使用してソリューションを解析して取得するにはどうすればよいですか?

4

5 に答える 5

5
int Count = doc.SelectNodes("Employee").Count;
于 2013-07-16T13:57:19.633 に答える
4

XPathを使用できます

var xdoc = XDocument.Load(path_to_xml);
var employeeCount = (double)xdoc.XPathEvaluate("count(//Employee)");
于 2013-07-16T14:02:49.393 に答える
2
XmlDocument doc = new XmlDocument();
doc.LoadXml(XmlString);

XmlNodeList list = doc.SelectNodes("Root/EmployeeList/Employee");
int numEmployees = list.Count;

xml がファイルからのものである場合は、

doc.Load(PathToXmlFile);
于 2013-07-16T13:57:33.347 に答える
2

linq to xml を使用すると、次のことができます。

XElement xElement = XElement.Parse(xml);
int count = xElement.Descendants("Employee").Count();

これは、xml が文字列 xml に含まれていることを前提としています。

于 2013-07-16T13:58:56.593 に答える
1

System.Xml.Linq代わりにライブラリを使用することを強くお勧めします。使用しようとしているものよりもはるかに優れています。XDocument をロードしたら、ルート ノードを取得して、次の行に沿って何かを実行できます。

//Parse the XML into an XDocument
int count = 0;

foreach(XElement e in RootNode.Element("EmployeeList").Elements("Employee"))
  count++;

このコードは正確ではありませんが、より複雑な例についてはこちらをご覧ください: http://broadcast.oreilly.com/2010/10/understanding-c-simple-linq-to.html

于 2013-07-16T14:11:33.127 に答える