Python's xml.etree getiterator equivalent to C#
I have this XML file : http://dl.dropbox.com/u/10773282/2011/perf.xml
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
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").El开发者_如何学Pythonements("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);
}
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;
Try:
using System.Xml;
// ...
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
var matches = xmlDoc.SelectNodes("//Class/ClassKeyName");
精彩评论