Solved

How Do I Use C# To Read XML Sub Elements

Posted on 2008-06-14
6
1,386 Views
Last Modified: 2010-04-21
Hello.
I am having a problem trying to read sub elements in an XML document.  Here is a simple example of the XML document I am currently able to read:

<?xml version="1.0" encoding="utf-8"?>
<WorkTeams>
    <WorkTeam Name="BlueTeam">
        <HomeBase>Los Angeles</HomeBase>
        <Vehicles>35</Vehicles>
    </WorkTeam>
    <WorkTeam Name="RedTeam">
        <HomeBase>San Diego</HomeBase>
        <Vehicles>20</Vehicles>
    </WorkTeam>
</WorkTeams>

I am able to read the above simple XML document with the following c# code:

        private void ReadXMLVehicleInfo()
        {
            String HomeBase = "";
            String Vehicles = "";

            DataSet ds = new DataSet();
            ds.ReadXml("c:\\VehicleTeams.xml");

            DataRow[] drs = ds.Tables["WorkTeam"].Select("Name = 'BlueTeam' ");
            if (drs.Length != 0)
            {
                HomeBase = drs[0]["HomeBase"].ToString();
                Vehicles = drs[0]["Vehicles"].ToString();
            }
            else
            {
            }
        }

My problem begins when I tried to introduce an element, (VehicleMfgs), with sub elements, (VehicleMfg),such as in the following XML document:

<?xml version="1.0" encoding="utf-8"?>
<WorkTeams>
    <WorkTeam Name="BlueTeam">
        <HomeBase>Los Angeles</HomeBase>
        <Vehicles>35</Vehicles>
        <VehicleMfgs>
            <VehicleMfg>Toyota</VehicleMfg>
            <VehicleMfg>Nissan</VehicleMfg>
            <VehicleMfg>Volvo</VehicleMfg>
        </VehicleMfgs>
    </WorkTeam>
    <WorkTeam Name="RedTeam">
        <HomeBase>San Diego</HomeBase>
        <Vehicles>20</Vehicles>
        <VehicleMfgs>
            <VehicleMfg>Ford</VehicleMfg>
            <VehicleMfg>Dodge</VehicleMfg>
            <VehicleMfg>Suzuki</VehicleMfg>
        </VehicleMfgs>
    </WorkTeam>
</WorkTeams>

How do I get a collection or list of the VehcleMfgs given that I know table will be WorkTeam and Name will be RedTeam?  The above code approach does not handle sub lists like the the one above with 3 different vehicle mfgs (i.e. Ford, Dodge, Suzuki).  Perhaps I should not be using a dataset or datatable.  Please advise if there is another way to do this with not much effort but while still using .NET XML classes.  
Thanks in advance.
0
Comment
Question by:zonkerman
  • 4
6 Comments
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 21787364
Where did the XML came from?
Why are you creating it's schema by hand?

The easiest way to do this is to create a type dataset with your schema. Fill the dataset with your data and serialize it (WriteXML). Reading it is as easy as ds.ReadXML.

What you're doing right now isn't a dataset, it's nested classes...
A colletion of a class  WorkTeams that have 3 public properties:
HomeBase (string)
Vehicles (int)
VehicleMfgs that is a collection of a class VehicleMfg.

So, or you use the XMLReader to loop through the nodes or you create a class hierarchy to map your structure... yet, I think it's much easier to use the dataset directly.

0
 
LVL 1

Author Comment

by:zonkerman
ID: 21787402
Hello AlexCode.
The XML is created by a c# utility that performs something like the following:

        private void WriteXMLConfigInfo()
        {            
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = ("    ");
            XmlWriter writer = XmlWriter.Create("c:\\VehicleTeams.xml", settings);
                // Write XML data.

            //Use automatic indentation for readability.
           // writer.Formatting = Formatting.Indented;

            //Write the XML delcaration.
            writer.WriteStartDocument();

            //Write the root element
            writer.WriteStartElement("WorkTeams");

            //Start an element
            writer.WriteStartElement("WorkTeam");

            //Add an attribute to the previously created element
            writer.WriteAttributeString("Name", "BlueTeam");

            //add sub-elements
            writer.WriteElementString("HomeBase", "Los Angeles");
            writer.WriteElementString("Vehicles", "35");
.......

The utility provides a gui for a user to setup information needed by an application.  I need for the user to create the necessary information with a gui rather than expect them to edit an xml file by hand.  The utility works fine so far but now I need to deal with a list of sub elements as I described in the first note.  I have used an XMLReader before but I am looking for a way to directly access the section of the XML file rather than have to iterate through checking for the right area.  That is why I was using the instance of a Dataset class followed by an instance collection of DataRow class so I could use the "select" filter ability.  I'm sure this could be done with LINQ but I won't be up to speed on LINQ for a while.  So I am seeking a way to have my C# code jump the the relevant area of the XML document then extract the information that pertains to that section (data row) for a given team name.
0
 
LVL 1

Author Comment

by:zonkerman
ID: 21787517
For now I have found that if I change the XML format to the following then the original C# code I have will handle the list of vehicle manufacturers:

<?xml version="1.0" encoding="utf-8"?>
<WorkTeams>
    <WorkTeam Name="BlueTeam">
        <HomeBase>Los Angeles</HomeBase>
        <Vehicles>35</Vehicles>
        <VehicleMfgs>Toyota,Nissan,Volvo</VehicleMfg>
    </WorkTeam>
    <WorkTeam Name="RedTeam">
        <HomeBase>San Diego</HomeBase>
        <Vehicles>20</Vehicles>
        <VehicleMfgs>Ford,Dodge,Suzuki</VehicleMfgs>
    </WorkTeam>
</WorkTeams>

Unfortunately with the new format I have to parse out the list of vehicle manufacturers which are now delimited by commas rather than listed as separate elements as before.  If anyone can provide a way to access the VehicleMfgs as I had listed in the first example which was as follows:
<VehicleMfgs>
        <VehicleMfg>Ford</VehicleMfg>
        <VehicleMfg>Dodge</VehicleMfg>
        <VehicleMfg>Suzuki</VehicleMfg>
  </VehicleMfgs>

then please provide an example of how it can be done.  Thanks in advance.

0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 13

Accepted Solution

by:
joechina earned 500 total points
ID: 21794712
XPathDocument xDoc = new XPathDocument(new StringReader(xml));
            XPathNavigator xNav = xDoc.CreateNavigator();
            XPathNodeIterator xi = xNav.Select(@"/WorkTeams/WorkTeam[@Name=""RedTeam""]/VehicleMfgs/VehicleMfg");
            List<string> result = new List<string>();
            while (xi.MoveNext())
            {
                result.Add(xi.Current.Value);
            }
0
 
LVL 1

Author Comment

by:zonkerman
ID: 21801324
Hello joechina.
Thank you for your solution.  Your sample code is direct, to the point, and exactly what I was looking for.  Good Job!

0
 
LVL 1

Author Closing Comment

by:zonkerman
ID: 31467292
Thanks joechina.  Your solution is direct, to the point, and exactly what I was hoping for.  Good Job!
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now