簡體   English   中英

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

[英]How can I read specific elements from XML string using XMLREADER in C#

我有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");
}

當然,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);

試試這個:

    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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM