我有一个XML字符串:
<GroupBy Collapse=\"TRUE\" GroupLimit=\"30\">
<FieldRef Name=\"Department\" />
</GroupBy>
<OrderBy>
<FieldRef Name=\"Width\" />
</OrderBy>
我是C#的新手。我尝试读取FieldRef元素的Name属性,但无法做到。我使用了XMLElement,是否有任何方法可以获取这两个值?
我有一个XML字符串:
<GroupBy Collapse=\"TRUE\" GroupLimit=\"30\">
<FieldRef Name=\"Department\" />
</GroupBy>
<OrderBy>
<FieldRef Name=\"Width\" />
</OrderBy>
我是C#的新手。我尝试读取FieldRef元素的Name属性,但无法做到。我使用了XMLElement,是否有任何方法可以获取这两个值?
尽管发布了无效的XML(没有根节点),但遍历<FieldRef>元素的简单方法是使用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");
}
当然,如果您的.NET框架中提供了LINQ to XML,那么它会提供更灵活和流畅的界面,也许使用它会更容易?代码如下:
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<string> names = doc.Root.Descendants("FieldRef").Select(e => e.Attribute("Name").Value);
IEnumerable<KeyValuePair<XElement, string>> pairings = doc.Root.Descendants("FieldRef").Select(e => new KeyValuePair<XElement, string>(e.Parent, e.Attribute("Name").Value));
- James ShuttlerXDocument doc = XDocument.Parse({xml});
静态方法,该方法在 MSDN 上有文档说明。 - James Shuttler试试这个:
string xml = "<GroupBy Collapse=\"TRUE\" GroupLimit=\"30\"><FieldRef Name=\"Department\" /></GroupBy><OrderBy> <FieldRef Name=\"Width\" /></OrderBy>";
xml = "<root>" + xml + "</root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlNode node in doc.GetElementsByTagName("FieldRef"))
Console.WriteLine(node.Attributes["Name"].Value);