如何在C#中使用XMLREADER从XML字符串中读取特定元素

我有XML字符串:

      

我是C#的新手。 我试图读取两个元素的FieldRef元素的Name属性,但我不能。 我用过XMLElement,有没有办法选择这两个值?

尽管发布了无效的XML(没有根节点),但是迭代元素的一种简单方法是使用XmlReader.ReadToFollowing方法:

 //Keep reading until there are no more FieldRef elements while (reader.ReadToFollowing("FieldRef")) { //Extract the value of the Name attribute string value = reader.GetAttribute("Name"); } 

当然,LINQ to XML提供了一个更灵活,更流畅的界面,如果在你所针对的.NET框架中可用的话,它可能会更容易使用吗? 代码然后变成:

 using System.Xml.Linq; //Reference to your document XDocument doc = {document}; /*The collection will contain the attribute values (will only work if the elements are descendants and are not direct children of the root element*/ IEnumerable names = doc.Root.Descendants("FieldRef").Select(e => e.Attribute("Name").Value); 

试试这个:

  string xml = " "; xml = "" + xml + ""; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); foreach (XmlNode node in doc.GetElementsByTagName("FieldRef")) Console.WriteLine(node.Attributes["Name"].Value);