[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 371
  • Last Modified:

how to read through all elements of a XML file in C#

XML file:

hi, anyone know some function or class or some code to read all element under a Element(parent) like <A>. This parent can has many child and sub childs, and sub sub childs ........So when user select element A then program can list  a2 .....a5 and more in some sub level.
If user select a3, then the program list sub elements and its childs from a4.......
Thank you
  • 2
1 Solution
The concept is simple, but the most practical approach to coding this depends on your XML structure and what information you need. Anyway,

using System.Xml;

XmlDocument d = new XmlDocument();
d.LoadXml("xml goes here"); // You can also use Load() to load from a file

XmlNode root = d.DocumentElement;

Now, root.ChildNodes returns a collection of the immediate children of the root node - they're also XmlNodes with possible ChildNodes again. One approach is to go through ChildNodes recursively, another one involves using the XPath query language. Unless you know XPath, stick with going through the ChildNodes collections.
therock_80Author Commented:
hi der_jth, can i use XML as a database? though i know it as data format, but if i can be a database, how can i make this xml file security. For example, i dont want any one access this XML file except me.
The answer to that question isn't particularly simple, but the short version: You can use XML documents as a sort of database - see the XmlDataDocument class and a good ADO.net book. File security is achieved through normal file system access control lists.

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now