Ruttensoft
asked on
XML question
I have this in a string:
<Hello Value="Test">Something></H ello><Hell o Value="Test2">Something2>< /Hello>
How can I parse each Hello-Element? So first the first Hello, then the second Hello in XML?
Thanks
<Hello Value="Test">Something></H
How can I parse each Hello-Element? So first the first Hello, then the second Hello in XML?
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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();
}
}
}
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.Inn erText);
Console.WriteLine(node.Att ributes[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.
XmlDocument xdoc = new XmlDocument;
XmlNodeList nodes;
xdoc.LoadXml(your_string);
nodes = xdoc.SelectNodes("//Hello"
foreach (XmlNode node in nodes)
{
Console.Writeline(node.Inn
Console.WriteLine(node.Att
}
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.
ASKER