1

I have this XML file : http://dl.dropbox.com/u/10773282/2011/perf.xml

enter image description here

It has two Class elements as is marked. I need to get two nodes with C#.

With Python, I can easily get them with etree.ElementTree as follows.

from xml.etree import ElementTree as et
from xml.etree.ElementTree import Element

tree = et.parse("perf.xml")
tss = tree.getiterator('Class')

for elem in tss:
    tss_name =  elem.find('ClassKeyName')
    print tss_name.text

>> helloclass.exe
>> helloclass.exeFpga::TestMe

enter image description here

How can I do the same thing with C#?

SOLVED

using System;
using System.Xml;
using System.Xml.Linq;
using System.Linq;

namespace HIR {
  class Dummy {

    static void Main(String[] argv) {

        XDocument doc = XDocument.Load("perf.xml");
        var res = from p in doc.Root.Elements("Module").Elements("NamespaceTable").Elements("Class").Elements("ClassKeyName")  select p.Value;

        foreach (var val in res) {
            Console.WriteLine(val.ToString());
        }
    }
  }
}

>> helloclass.exe
>> helloclass.exeFpga::TestMe

Or

foreach (var elem in elems) {
    var res = elem.Elements("ClassKeyName").ToList();
    Console.WriteLine(res[0].Value);
}
prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

1

You should try Linq to XML... Quite easy to use:

var xml = XDocument.Load(filename);
var res = from p in xml.Root.Elements("Class").Elements("ClassKeyName") select p.Value;
xanatos
  • 109,618
  • 12
  • 197
  • 280
0

Try:

using System.Xml;
// ...
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
var matches = xmlDoc.SelectNodes("//Class/ClassKeyName");
Lucas Jones
  • 19,767
  • 8
  • 75
  • 88