我有这个XML文件:http://dl.dropbox.com/u/10773282/2011/perf.xml
标记有两个Class元素。我需要用C#获得两个节点。
使用Python,我可以使用etree.ElementTree轻松获取它们,如下所示。
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
我怎样才能用C#做同样的事情?
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
或者
foreach (var elem in elems) {
var res = elem.Elements("ClassKeyName").ToList();
Console.WriteLine(res[0].Value);
}
答案 0 :(得分:1)
您应该尝试使用Linq to XML ...非常容易使用:
var xml = XDocument.Load(filename);
var res = from p in xml.Root.Elements("Class").Elements("ClassKeyName") select p.Value;
答案 1 :(得分:0)
尝试:
using System.Xml;
// ...
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
var matches = xmlDoc.SelectNodes("//Class/ClassKeyName");