tags:

views:

42

answers:

4

I have an xml that looks like this

<words>
     <word>word1</word>
     <word>word2</word>
     <word>word3</word>
     <word>word4</word>
</words>

I would like to loop through the "word" tags and just output the innertext for now. how would I do this?

here is what i am doing now but is says the list of nodes count is 1

        string _badWordFileDocPath = //my file path;
        XmlDocument badWordDoc = new XmlDocument();
        badWordDoc.Load(_badWordFileDocPath);


        XmlElement root = badWordDoc.DocumentElement;
        XmlNodeList nodes = root.SelectNodes("/words");
        foreach(XmlNode node in nodes)
        {
            Console.WriteLine(node.InnerText);
        }

Thanks!

+4  A: 

You are selecting the root words node itself, rather than the child word nodes. Add /word to your XPath:

XmlNodeList nodes = root.SelectNodes("/words/word");
Quartermeister
Thank you this was the quickest fix and worked perfectly. Thank you !
twal
+2  A: 

You need to move down the node tree one more layer:

foreach(XmlNode node in nodes)
 {
     XmlNodeList innerNodes = node.SelectNodes("/word");
     foreach(Xmlnode innerNode in innerNodes )
     {
          Console.WriteLine(innerNode.InnerText);
     }
 }
yhw
+1  A: 

You are missing /word in your XPath.

You can also use Linq (XDocument) to fetch the data.

MSI
+2  A: 

I'd recommend using the classes in System.Xml.Linq for this task:

XElement wordsElement = XElement.Parse(yourXmlText);

var words = from w in wordsElement.Elements("word")
            select w.Value;
Dan Tao
Thank you I may change to using linq as you suggest.
twal