如何在 C# 中使用 XMLREADER 从 XML 字符串中读取特定元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8888806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I read specific elements from XML string using XMLREADER in C#
提问by Waleed
I have XML String:
我有 XML 字符串:
<GroupBy Collapse=\"TRUE\" GroupLimit=\"30\">
<FieldRef Name=\"Department\" />
</GroupBy>
<OrderBy>
<FieldRef Name=\"Width\" />
</OrderBy>
I am new in C#. I tried to read the Name attribute of the FieldRef element for both elements but I could not. I used XMLElement , is there any way to pick these two values?
我是 C# 新手。我试图读取两个元素的 FieldRef 元素的 Name 属性,但我不能。我使用了 XMLElement ,有什么办法可以选择这两个值吗?
采纳答案by James Shuttler
Despite the posting of invalid XML (no root node), an easy way to iterate through the <FieldRef> elements is to use the XmlReader.ReadToFollowingmethod:
尽管发布了无效的 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");
}
Of course a more flexible and fluent interface is provided by LINQ to XML, perhaps it would be easier to use that if available within the .NET framework you are targeting? The code then becomes:
当然,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<string> names = doc.Root.Descendants("FieldRef").Select(e => e.Attribute("Name").Value);
回答by ojlovecd
try this:
尝试这个:
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);

