ITsolutionWizard
asked on
xml node
In c#, how to read all child, not one by one?
string xmlString = "<people><firstname>John</firstname><lastname>John</lastname></people>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
foreach (XmlNode node in xmlDoc.SelectNodes("//people"))
{
//how to loop and read all child?
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
First of all: when using XPath, then avoid the // syntax, cause it is much slower then the exact XPath /People.
Reading every node is pretty simple using XmlDocument:
But I prefer normally strong types using deserialization:
But the questions on my side is similar to Bill's: What is your goal here?
Reading every node is pretty simple using XmlDocument:
namespace ConsoleCS
{
using System;
using System.Xml;
public class Program
{
public static void Main(string[] args)
{
string xmlString = "<people><firstname>John</firstname><lastname>NotJohn</lastname></people>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
foreach (XmlNode node in xmlDoc.SelectNodes("/people"))
{
Console.WriteLine(node.SelectSingleNode("firstname").InnerText);
Console.WriteLine(node.SelectSingleNode("lastname").InnerText);
}
Console.WriteLine("\nDone.");
Console.ReadLine();
}
}
}
Using XDocument instead of XmlDocument is in many cases simpler as already shown by Misha.But I prefer normally strong types using deserialization:
namespace ConsoleCS
{
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
[XmlRoot("people")]
public class People
{
[XmlElement("firstname")]
public string FirstName { get; set; }
[XmlElement("lastname")]
public string LastName { get; set; }
public override string ToString()
{
return string.Format($"{LastName}, {FirstName}");
}
}
public class Program
{
public static void Main(string[] args)
{
string xmlString = "<people><firstname>John</firstname><lastname>NotJohn</lastname></people>";
People people;
XmlSerializer serializer = new XmlSerializer(typeof(People));
using (TextReader reader = new StringReader(xmlString))
{
people = (People)serializer.Deserialize(reader);
}
Console.WriteLine(people);
Console.WriteLine("\nDone.");
Console.ReadLine();
}
}
}
But the questions on my side is similar to Bill's: What is your goal here?
Typically any result of gathering matches from XML will yield a collection that then can be iterated over, do you not want to do that? And if so, what format do you want all the matches to be in?
»bp