2009-11-01 105 views
5

我有几个XML文件,我希望从中读取属性。我的主要目标是将语法突出显示应用于富文本框。如何读取C#中的XML属性?

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

那么,如何获取属性name的值,并将它们置于每个XML文件的字符串集合中。

我使用Visual C#2008

回答

4

其他的答案将做的工作 - 但语法高亮啄几个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后,你尝试了直接的选项,你不满意的表现。

+0

这正是我需要的,但是......我如何将“无论”作为一个字符串数组? – 2009-11-01 13:26:00

+0

对于语法高亮显示,我非常怀疑他会一遍又一遍地读取文件。显而易见的解决方法是一次*读*,这意味着速度远不如可读性重要。使用LINQ to XML是这里的显而易见的解决方案,IMO。 – 2009-11-01 13:57:26

+0

@JonSkeet我同意 - 事实上,我建议仅考虑这种方法,如果性能变成问题(例如 - 读取文件一次 - 可能是这种情况,这需要在大量大文件上执行并且启动/负载性能可能会受到显着影响) – JohnIdol 2009-11-01 17:00:32

3

您可以使用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表达式表示,关键词‘“的文件,命名中的所有元素’

编辑:刚才看到你只想要一个名为关键字元素更新的代码示例

+0

如何为XDocument提供我的XML文档的值?在Visual C#中,在解决方案资源管理器中,我有一个名为API的文件夹,里面是所有的XML文档,例如:batch.xml。我是否将它实例化为一个String或什么? – 2009-11-01 13:10:28

+0

@Mohit:'XDocument doc = XDocument.Load(@“API \ batch.xml”);'应该这样做 – 2009-11-01 14:39:42

+0

我得到了“解析EntityName时发生错误,第1120行,第27位。这是第1120行:位置27介于e和r之间 – 2009-11-04 01:39:18

0

您可以使用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 
      }; 
0

你可能会希望使用XPath。 //Keyword/@name应该为您提供所有关键字名称。

这里有一个很好的介绍:.Net and XML XPath Queries

3

与其他人一样,我会建议使用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(); 
} 

另外请注意,这只是给你的名字 - 我本来期望你想要的元素的其他细节,在这种情况下,你可能想要的东西略有不同。如果事实证明你需要更多,请告诉我们。

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

        } 
       } 

    }