我会在System.Xml.Linq中使用XLINQ类(这是需要引用的名称空间和程序集)。加载XML到和的XDocument:
XDocument doc = XDocument.Parse(someString);
接下来,你可以使用递归或者伪递归循环遍历子节点。你可以选择你的子节点,如:
//if Directory is tag name of Directory XML
//Note: Root is just the root XElement of the document
var directoryElements = doc.Root.Elements("Directory");
//you get the idea
var fileElements = doc.Root.Elements("File");
变量directoryElements和fileElements将IEnumerable的类型,这意味着你可以使用像通过所有元素的一个foreach循环。建立你的元素的一种方法是这样的:
List<MyFileType> files = new List<MyFileType>();
foreach(XElelement fileElement in fileElements)
{
files.Add(new MyFileType()
{
Prop1 = fileElement.Element("Prop1"), //assumes properties are elements
Prop2 = fileElement.Element("Prop2"),
});
}
在这个例子中,MyFileType是您创建表示文件类型。这是一种暴力攻击,但它会完成工作。
如果你想使用XPath,你将需要使用 System.Xml.XPath。
上的System.Xml的注VS System.Xml.Linq的
有许多自1.0天数一直在净XML类。这些生活(主要)在System.Xml中。在.Net 3.5中,一系列新的XML类在System.Xml.Linq下发布。我不能过分强调它们比System.Xml中的旧类更合适。我强烈建议他们去.Net程序员,尤其是刚刚进入.Net/C#的人。
我问了一个类似的问题,按照链接看到一个很好的讨论: http://stackoverflow.com/questions/9371541/how-to-create-a-collection-from-list-of-strings-that -represents-a-directory-stru – geekzster 2012-04-03 19:16:08