簡體   English   中英

如何在C#中讀取XML屬性?

[英]How to read XML attributes in C#?

我有幾個XML文件,我希望從中讀取屬性。 我的主要目標是將語法突出顯示應用於富文本框。

例如,在我的一個XML文檔中,我有: <Keyword name="using">[..]所有文件都具有相同的元素: Keyword

那么,我如何獲取屬性name的值並將它們放在每個XML文件的字符串集合中。

我正在使用Visual C#2008。

其他答案將完成這項工作 - 但語法突出顯示東西和你說的幾個xml文件讓我覺得你需要更快的東西,為什么不使用精簡和平均的XmlReader

private string[] getNames(string fileName)
{

  XmlReader xmlReader = XmlReader.Create(fileName);
  List<string> names = new List<string>(); 

  while (xmlReader.Read())
  {
   //keep reading until we see your element
   if (xmlReader.Name.Equals("Keyword") && (xmlReader.NodeType == XmlNodeType.Element))
   {
     // get attribute from the Xml element here
     string name = xmlReader.GetAttribute("name");
     // --> now **add to collection** - or whatever
     names.Add(name);
   }
  }

  return names.ToArray();
}

另一個不錯的選擇是XPathNavigator類 - 它比XmlDoc更快,你可以使用XPath。

此外,我建議你與你不滿意的性能直接的選項后嘗試用這種方法去只有IFF。

您可以使用XPath獲取所有元素,然后使用LINQ查詢獲取您找到的所有名稱atttributes的值:

 XDocument doc = yourDocument;
 var nodes = from element in doc.XPathSelectElements("//Keyword")
             let att = element.Attribute("name")
             where att != null
             select att.Value;
 string[] names = nodes.ToArray();

//關鍵字XPath表達式表示“文檔中的所有元素,名為”關鍵字“。

編輯 :剛看到你只想要名為Keyword的元素。 更新了代碼示例。

像其他人一樣,我建議使用LINQ to XML - 但我認為這里不需要使用XPath。 這是一個返回文件中所有關鍵字名稱的簡單方法:

static IEnumerable<string> GetKeywordNames(string file)
{
    return XDocument.Load(file)
                    .Descendants("Keyword")
                    .Attributes("name")
                    .Select(attr => attr.Value);
}

很好,聲明:)

請注意,如果您想要多次使用結果,則應在其上調用ToList()ToArray() ,否則每次都會重新加載文件。 當然,您可以通過將相關調用添加到方法調用鏈的末尾來更改方法以返回List<string> or string[] ,例如

static List<string> GetKeywordNames(string file)
{
    return XDocument.Load(file)
                    .Descendants("Keyword")
                    .Attributes("name")
                    .Select(attr => attr.Value)
                    .ToList();
}

還要注意,這只是給你的名字 - 我希望你想要你的元素的其他細節,在這種情況下,你可能想要一些略有不同的東西。 如果事實證明您需要更多,請告訴我們。

**<Countries>
  <Country name ="ANDORRA">
    <state>Andorra (general)</state>
    <state>Andorra</state>
  </Country>
  <Country name ="United Arab Emirates">
    <state>Abu Z¸aby</state>
    <state>Umm al Qaywayn</state>
  </Country>**



 public void datass(string file)
  {

            string file = HttpContext.Current.Server.MapPath("~/App_Data/CS.xml");
                XmlDocument doc = new XmlDocument();
                if (System.IO.File.Exists(file))
                {
                    //Load the XML File
                    doc.Load(file);

                }


                //Get the root element
                XmlElement root = doc.DocumentElement;
                XmlNodeList subroot = root.SelectNodes("Country");

                for (int i = 0; i < subroot.Count; i++)     
                {

                    XmlNode elem = subroot.Item(i);
                    string attrVal = elem.Attributes["name"].Value;
                    Response.Write(attrVal);
                    XmlNodeList sub = elem.SelectNodes("state");
                    for (int j = 0; j < sub.Count; j++)
                    {
                        XmlNode elem1 = sub.Item(j);
                        Response.Write(elem1.InnerText);

                    }
                }

    }

您可以使用LINQ to XML。

例:

var xmlFile = XDocument.Load(someFile);
var query = from item in xmlFile.Descendants("childobject")
            where !String.IsNullOrEmpty(item.Attribute("using")
            select new 
            {
                AttributeValue = item.Attribute("using").Value
            };

你可能想要使用XPath。 //Keyword/@name應該為您提供所有關鍵字名稱。

這是一個很好的介紹: .Net和XML XPath查詢

暫無
暫無

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

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