Search code examples
c#xmlreader

Getting File Attributes with XMLReader in C#


I used the XMLReader format:


XmlReader xmlReader = XmlReader.Create("batch.xml");
while (xmlReader.Read())
{
    //Keep reading
    if (xmlReader.Name.Equals("Keyword") && (xmlReader.NodeType == XmlNodeType.Element))
    {
        // get attribute from the Xml element here
        string keywords = xmlReader.GetAttribute("name"); 
    }
}

How do I cast "keywords" as a String[]?


Solution

  • It depends.

    If your XML has a single name attribute that contains multiple keywords, call String.Split, like this:

    string[] keywords = xmlReader.GetAttribute("name").Split(' ');
    

    If you have multiple name attributes or Keyword elements, create a List<string> and fill it up in a loop, like this:

    List<string> keywords = new List<string>();
    XmlReader xmlReader = XmlReader.Create("batch.xml");
    while (xmlReader.Read()) {
        //Keep reading
        if (xmlReader.Name.Equals("Keyword") && (xmlReader.NodeType == XmlNodeType.Element))
            keywords.Add(xmlReader.GetAttribute("name")); 
    }
    

    If you really need a string[], you can call keywords.ToArray().