简体   繁体   中英

Accessing the Xml nodes through iteration c#

So I just started using c# about a day ago and haven't had too many issues with it so far but I'm working on an bot for Discord that will pull Pokemon info from an api. I'm currently stuck on traversing through the xml. Here's part of the xml I'm trying to work with:

<?xml version="1.0" encoding="UTF-8"?>
    <root>
        <stats>
            <stat>
                <url>https://pokeapi.co/api/v2/stat/6/</url>
                <name>speed</name>
            </stat>
            <effort>0</effort>
            <base_stat>100</base_stat>
        </stats>
    </root>

That's basically an abridged version of my xml doc but there are multiple nodes for "stats". I want to loop the the stats nodes and pull the name of the stat and the value for base stat. Everything I've tried so far throws a null exception error. I having trouble trying to understand how to correctly parse xml so any help would be greatly aprreciated. Also just for extra info I'm working with XmlDocuments. Here's basically what ive tried so far:

XmlDocument pokemon = new XmlDocument();
pokemon.Load("c:\\document.xml");
XmlNodeList xmlNodes = pokemon.SelectNodes("/root/stats");
int count = 0;
foreach (XmlNode xmlNode in xmlNodes)
{
    temp.stats[count].val = xmlNode["/stat/name"].InnerText;
    temp.stats[count++].num = xmlNode["base_stat"].InnerText;
}

temp is of type poke and stats is just a type I made that has two strings in it, one for the name of the stat and another for the value of the stat. I was able to access other things from the xml document perfectly fine but I'm having trouble pulling from nodes that share the same name.

I believe this will set you on the right path:

XmlNodeList xmlNodes = pokemon.SelectNodes(@"//root/stats");
int count = 0;

foreach (XmlNode xmlNode in xmlNodes)
{
    temp.stats[count].val = xmlNode.SelectSingleNode("stat/name").InnerText;
    temp.stats[count++].num = xmlNode.SelectSingleNode("base_stat").InnerText; 
}

First, to reference the root node with XPath, you need the double forward slashes // . Secondly, you need to use xmlNode.SelectSingleNode(string xPath) , and your XPath shouldn't have the leading forward slash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM