Link to home
Start Free TrialLog in
Avatar of Ruttensoft
Ruttensoft

asked on

XML question

I have this in a string:

<Hello Value="Test">Something></Hello><Hello Value="Test2">Something2></Hello>

How can I parse each Hello-Element? So first the first Hello, then the second Hello in XML?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Reza Rad
Reza Rad
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ruttensoft
Ruttensoft

ASKER

Thanks
why do you use one more close > symbol after something?.

check the following code
using System;
using System.Xml;

namespace ReadXMLfromFile
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class Class1
    {
        static void Main(string[] args)
        {
            XmlTextReader reader = new XmlTextReader ("books.xml");
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element: // The node is an element.
                        Console.Write("<" + reader.Name);
                        Console.WriteLine(">");
                        break;
                    case XmlNodeType.Text: //Display the text in each element.
                        Console.WriteLine (reader.Value);
                        break;
                    case XmlNodeType.EndElement: //Display the end of the element.
                        Console.Write("</" + reader.Name);
                        Console.WriteLine(">");
                        break;
                }
            }
            Console.ReadLine();
        }
    }
}
      
You can create an XmlDocument object and then load your text as xml and use an XPath query to select the appropriate nodes:

    XmlDocument xdoc = new XmlDocument;
    XmlNodeList nodes;

    xdoc.LoadXml(your_string);
    nodes = xdoc.SelectNodes("//Hello");

    foreach (XmlNode node in nodes)
    {
        Console.Writeline(node.InnerText);
        Console.WriteLine(node.Attributes[0].InnerText);
    }

The only not I would point out is that you technically don't have valid XML since there is no root node in  our example. I wrapped your data in a  element and was able to display the data with the above code.