Solved

Looping through an XML document

Posted on 2004-04-04
7
285 Views
Last Modified: 2013-11-19
I have an XML document similar to the one below that I need to process and display in a windows fomm using a combination of tree-view and list view controls in C#.  The element <Company> is the only one that I can guarantee will come in the same standard format each time the XML is created and I need to display that separately on the windows form.  The rest of the elements can change and could possibly more nested elements within them.  What is the best way to loop through such an XML document and display the contents?  I am a novice XML user so any help will be appreciated.  Also, what is the determining factor in using the XML document object Vs XmlTextReader?  Thanks.


"test.xml"

<?xml version="1.0" encoding="utf-8"?>
<Company>
<name>x</name>
<address>y</address>
<sector>z</sector>
</Company>
<Departments>
<Sales>
<President>
<First Name>Peter</First Name>
<Last Name>Pan</Last Name>
<Age>45</Age>
</President>
<VP>
<First Name>John</First Name>
<Last Name>Doe</Last Name>
<Age>35</Age>
</VP>
<Sales>
</Departments>
 
0
Comment
Question by:fifo123
  • 3
  • 2
7 Comments
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10752589
The best thing for you is to use the Xml namespace. In the beginning of your file include:

using System.Xml;

Then you can use the power of the XmlDocument and XmlNode classes. This is a huge area, so I will just tell you that you can use for example the Load method of the XmlDocument to load the whole document.

You can start your investigation of the Xml namespace from here:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlxmldocumentclasstopic.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlxmlnodeclasstopic.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxml.asp
0
 

Author Comment

by:fifo123
ID: 10763026
Ok,
So, I kinda figured out how to recursively traverse through all the elements in the given XML.  Now, I'm wanting to display that using a treeview control.  The code below works fine but it displays the results as follows:

+Name
+Address
+Sector
+Departments
  +Sales
    +President
      +FirstName
      +LastName
      +Age

If I expand the Name node, I get the value " = 'x' " which is fine.  To see the value of the FirstName for the node President, I would have to expand that node.  How would I make it such that it will display:

Name = 'X'
Address = 'Y'
Sector = 'z'
+ President
  - FirstName = "John"
  - LastName = "Doe"


The XML document looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Company>
<name>x</name>
<address>y</address>
<sector>z</sector>
<Departments>
<Sales>
<President>
<FirstName>Peter</FirstName>
<LastName>Pan</LastName>
<Age>45</Age>
</President>
<VP>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Age>35</Age>
</VP>
</Sales>
</Departments>
</Company>

private void frmTest_Load(object sender, System.EventArgs e)
{
XmlDocument Doc = new XmlDocument();
Doc.Load(@"C:\test.xml");
XmlNodeList nodeList = Doc.SelectNodes("/Company");
foreach(XmlNode oNode in nodeList)
{
    DisplayNode(oNode, tview.Nodes);      
}
}

private void DisplayNode(XmlNode i_Node, TreeNodeCollection t_Nodes)
{
    string Text = "";
    foreach (XmlNode node in i_Node.ChildNodes)
    {                              
       if(node.Value != null)
            Text = " = '" + node.Value + "'";                              
       else if(node.Attributes != null && node.Attributes.Count > 0)
            Text = node.Attributes[0].Value;
       else
             strText = node.Name;

       TreeNode myNode = new TreeNode(strText);
       t_Nodes.Add(myNode);
       ProcessNode(node, myNode.Nodes);
}
}
0
 
LVL 20

Accepted Solution

by:
TheAvenger earned 50 total points
ID: 10763481
0
 

Author Comment

by:fifo123
ID: 10768339
TheAvenger..... Thanks for the tip.

I tried the sample from the microsoft site.  I used my XML document and it pretty much does what my code above does.  What I'm attempting to do is that if a node doesn't have any child nodes, display its name followed by its value.  For example:

for the element:

<name>x</name>, I want to display name='x'

and for the nested elements:

<Departments>
<Sales>
<President>
<FirstName>Peter</FirstName>
<LastName>Pan</LastName>
</President>
</Sales>
</Departments>

I want to display
-Departments
....-Sales
......-President
..........FirstName = 'Peter'
..........LastName = 'Pan'

What my code and the sample from microsoft is doing the following:
-Departments
.....-Sales
.......-President
.........-FirstName
.............Peter
.........-LastName
.............Pan

I've been trying for the last day and half, but no success yet.  Any suggestions?

0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10769134
have you tried something like:

XmlNode node = ....;  // Find the node or go over them recursively

if (node.ChildNodes.Count == 0)
  tree.Add (node.Value);

I am not sure the names of all these properties are correct, but this is the idea and you can find more on the link I gave you.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Preface This article introduces an authentication and authorization system for a website.  It is understood by the author and the project contributors that there is no such thing as a "one size fits all" system.  That being said, there is a certa…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

914 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

16 Experts available now in Live!

Get 1:1 Help Now