开发者

Getting File Attributes with XMLReader in C#

开发者 https://www.devze.com 2022-12-10 08:32 出处:网络
I used the XMLReader format: XmlReader xmlReader = XmlReader.Create(\"batch.xml\"); while (xmlReader.Read())

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"); 
   开发者_StackOverflow社区 }
}

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


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().


Since you're using a XmlReader, you can't have all nodes at once. You need to create a List<string> collection, populate and return it.

0

精彩评论

暂无评论...
验证码 换一张
取 消