繁体   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