C# 如何在C中使用XMLREADER从XML字符串中读取特定元素#
我有XML字符串:C# 如何在C中使用XMLREADER从XML字符串中读取特定元素#,c#,xml,C#,Xml,我有XML字符串: <GroupBy Collapse=\"TRUE\" GroupLimit=\"30\"> <FieldRef Name=\"Department\" /> </GroupBy> <OrderBy> <FieldRef Name=\"Width\" /> </OrderBy> 我是新来的。我试图读取这两个元素的FieldRef元素的Name属性,但无法
<GroupBy Collapse=\"TRUE\" GroupLimit=\"30\">
<FieldRef Name=\"Department\" />
</GroupBy>
<OrderBy>
<FieldRef Name=\"Width\" />
</OrderBy>
我是新来的。我试图读取这两个元素的FieldRef元素的Name属性,但无法读取。我使用了XMLElement,有没有办法选择这两个值?尽管发布了无效的XML(没有根节点),但迭代元素的一个简单方法是使用
XmlReader。ReadToFollow
方法:
//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<string> names = doc.Root.Descendants("FieldRef").Select(e => e.Attribute("Name").Value);
使用System.Xml.Linq;
//参考您的文档
XDocument doc={document};
/*集合将包含属性值(仅当元素
是根元素的子元素,不是根元素的直接子元素*/
IEnumerable Name=doc.Root.substands(“FieldRef”).Select(e=>e.Attribute(“Name”).Value);
试试这个:
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);
stringxml=”“;
xml=”“+xml+”;
XmlDocument doc=新的XmlDocument();
doc.LoadXml(xml);
foreach(doc.GetElementsByTagName(“FieldRef”)中的XmlNode节点)
Console.WriteLine(node.Attributes[“Name”].Value);
XML的其余部分是什么?有效的XML必须有一个根节点。问题是,此字符串不是固定的,有时它不包含GroupBy元素,有时它将包含OrderBy元素。我需要选择FieldRef,我应该知道它属于哪个根元素。我注意到FieldRef元素并不总是包含d在同一父节点中,子体将对此进行说明并提取它,而不管它嵌套在哪个元素中。如果您还希望使用LINQ to XML获取父元素,请尝试以下操作:IEnumerable pairings=doc.Root.subjections(“FieldRef”)。选择(e=>new KeyValuePair(e.parent,e.Attribute(“Name”).Value));
我有一个字符串而不是一个文件,我将如何定义doc变量?我看到它的XDocument类型,我如何将我的字符串链接到doc?@Waleed很抱歉,我没有意识到,只要字符串是有效的XML(你发布的XML不是,它需要根节点),那么你就可以使用XDocument doc=XDocument.Parse({XML})
static方法,该方法记录在上,非常抱歉,但我有一个错误:“System.Collections.Generic.IEnumerable”不包含“Select”的定义,并且找不到扩展方法“Select”接受类型为“System.Collections.Generic.IEnumerable”的第一个参数(是否缺少using指令或程序集引用?)我以前应该将e定义为XMLElement吗?我应该给它什么值?问题是,这个字符串不是固定的,有时它不包含GroupBy元素,有时它包含OrderBy元素。我需要选择FieldRef,我应该知道它属于哪个根元素。