Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > XML > XML
Password Reminder
Register
Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
XML General XML discussions.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the XML section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old December 17th, 2007, 06:22 PM
Authorized User
 
Join Date: Jan 2006
Location: , , .
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
Default Help Parsing XML File

I'm using a C# Console Application. I have an XML and matching XSD File. Here's a small sample of my XML:
<DataFile>
  <Header>
    <FileDate>5/23/2007 3:03:05 PM</FileDate>
    <FileVersion>SomeFileVersion</FileVersion>
    <AppType>NotDefined</AppType>
    <AcadLevel>Undergraduate</AcadLevel>
    <CampusCode>Madison</CampusCode>
    <ApplicationCount>18</ApplicationCount>
    <BatchID>cc71fd48-ff52-47ae-a753-3b92f5ebbd29</BatchID>
  </Header>
  <SubmittedApplications>
    <Application>
        <BIRTH_DATE>19720505</BIRTH_DATE>
        <FIRST_NAME>Mary</FIRST_NAME>
        <HSCOURSE id="1">
            <HSCOURSE_CREDITS>3</HSCOURSE_CREDITS>
            <HSCOURSE_DEPARTMENT>English</HSCOURSE_DEPARTMENT>
            <HSCOURSE_TERM>Fall Sem</HSCOURSE_TERM>
            <HSCOURSE_TERM_OTHER />
            <HSCOURSE_TITLE>British Literature</HSCOURSE_TITLE>
            <HSCOURSE_YEAR>20072008</HSCOURSE_YEAR>
        </HSCOURSE>
        <HSCOURSE id="2">
            <HSCOURSE_CREDITS>5</HSCOURSE_CREDITS>
            <HSCOURSE_DEPARTMENT>Chemistry</HSCOURSE_DEPARTMENT>
            <HSCOURSE_TERM>Acad Year</HSCOURSE_TERM>
            <HSCOURSE_TERM_OTHER />
            <HSCOURSE_TITLE>AP Chemistry</HSCOURSE_TITLE>
            <HSCOURSE_YEAR>20062007</HSCOURSE_YEAR>
        </HSCOURSE>
        <LAST_NAME>Mittelstadt</LAST_NAME>
    </Application>
  </SubmittedApplications>
</DataFile>

What I need to do is:
- pass in an array of node names e.g. string[] nodeList = { "FIRST_NAME", "LAST_NAME", "SSN", "BIRTH_DATE", "HSCOURSE" };
- loop through each application node in the XML file obtaining all instances for that application of the nodes (and their children if any) passed in the array including attributes for each of the nodes passed in
- write those values to screen then go to the next application in the file and so on.

I can load the xml into an XmlDocument and am able to create a nodelist containing all of the application nodes.

I cannot however get the sequence to allow me to loop through through the application nodes retrieving all the instances of the nodes passed in. For example there could be no <HS_COURSE> listings in which case it shows up as <HS_COURSE/> or there could be ten of them and I need to be able to grab them all.

How do I go about looping through each application obtaining all instances of the given nodes in the array as well as any child nodes that node may contain?

Reply With Quote
  #2 (permalink)  
Old December 18th, 2007, 05:15 AM
samjudson's Avatar
Friend of Wrox
Points: 8,687, Level: 40
Points: 8,687, Level: 40 Points: 8,687, Level: 40 Points: 8,687, Level: 40
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Aug 2007
Location: Newcastle, , United Kingdom.
Posts: 2,128
Thanks: 1
Thanked 189 Times in 188 Posts
Default

To loop through a selection of nodes in C# you can do the following:

foreach(XmlNode applicationNode in document.SelectNodes("//Application"))
{
   // Do something
}

You can do a similar thing for each element in your array:

foreach(string nodePattern in nodeList)
{
  foreach(XmlNode node in applicationNode.SelectNodes(nodePattern))
  {
     // Do something else
  }
}

At this point I would pass the XmlNode 'node' to a recursive function that prints out all attributes and then passes each child node to itself.

e.g.:

public static void PrintNode(XmlNode node)
{
  foreach(XmlNode attribute in node.Attributes)
  {
    Console.WriteLine(attribute.Name + " = " + attribute.Value);
  }
  foreach(XmlNode child in node.ChildNodes)
  {
    // print out name
    Console.Write(child.Name);
    // pass to recursive function.
    PrintNode(child);
  }
}


/- Sam Judson : Wrox Technical Editor -/
Reply With Quote
  #3 (permalink)  
Old December 18th, 2007, 02:50 PM
Authorized User
 
Join Date: Jan 2006
Location: , , .
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Thanks! I wasn't quite able toget it to work the way you laid it out but it was definitely close and it definitely does what it needs to so thanks a million for all your help!

Reply With Quote
  #4 (permalink)  
Old December 20th, 2007, 01:54 PM
Authorized User
 
Join Date: Jan 2006
Location: , , .
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
Default

It looks like I missed a piece. There are three nodes in application I am supposed to "remove" before wiritng it our. By "remove", I mean remove them from the in memory instacne loaded into the XmlDocument Object, and not from the actual physical file.

Can I do this through the XPATH query?

Reply With Quote
  #5 (permalink)  
Old December 20th, 2007, 02:00 PM
mhkay's Avatar
Wrox Author
Points: 18,438, Level: 59
Points: 18,438, Level: 59 Points: 18,438, Level: 59 Points: 18,438, Level: 59
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Apr 2004
Location: Reading, Berks, United Kingdom.
Posts: 4,954
Thanks: 0
Thanked 290 Times in 285 Posts
Default

You can use XPath to locate the nodes that you want to remove, but the actual removal needs to be done using the DOM methods.

(Of course this whole task would be much easier if you used a high-level language like XSLT or XQuery, but I assume you have a good reason for trying to do the job in C#).

Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference
Reply With Quote
  #6 (permalink)  
Old January 7th, 2008, 04:30 PM
Authorized User
 
Join Date: Jan 2006
Location: , , .
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I've got the loop through the XML working almost exactly like I want it. Almost. I need some help figuring out a problem with the recursion.

For elements in the XML where there is an attribute assigned and child nodes:
<ACTIVITIES id="1">
  <ACTIVITY>Debate Club</ACTIVITY>
  <ACTIVITY_HRS_WEEK>3</ACTIVITY_HRS_WEEK>
  <ACTIVITY_LEADERSHIP>President; Oration Trophy 2007; Midwest Debate Champion 2006</ACTIVITY_LEADERSHIP>
  <ACTIVITY_NO_YEARS>4</ACTIVITY_NO_YEARS>
</ACTIVITIES>
what I want to do is grab the value of the id attribute and then loop through the child nodes inserting each child node into the database like this:
FILE_DATE = File Date from XML File
TAG_NAME = ACTIVITY
TAG_ID = 1
TAG_VALUE = Debate Club
and so on for each child node. However I do not want the ACTIVITIES Tag itself entered at all.

If there is no attribute assigned I still want to insert it into the database like above, but the tag id is set 0;

Here's the Sample XML:
<?xml version="1.0"?>
<DataFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Header>
    <FileDate>10/24/2007 9:25:52 AM</FileDate>
    <FileVersion>0.1 - alpha</FileVersion>
    <AppType>Degree</AppType>
    <AcadLevel>Undergraduate</AcadLevel>
    <CampusCode>Oshkosh</CampusCode>
    <ApplicationCount>1</ApplicationCount>
    <BatchID>00000778</BatchID>
    <USResidency>USResident</USResidency>
    <SubAppType>Degree</SubAppType>
    <SubAcadLevel>Undergraduate</SubAcadLevel>
    <SubUSResidency>USResident</SubUSResidency>
  </Header>
  <Applications>
    <Application>
      <SavedApplicationID>175eca7e-6068-4bf2-b9ad-5794ca2bbccf</SavedApplicationID>
      <UniqueHash>00000778</UniqueHash>
      <ACAD_LEVEL>1</ACAD_LEVEL>
      <ACT>Y</ACT>
      <ACTIVITY_STATEMENT>The debate club is something I feel very strongly about. I am a very good orator; I primarily argue through repetition, and I invariably convince everybody I speak to. I am a very good orator; I primarily argue through repetition, and I invariably convince everybody I speak to. I am a very good orator; I primarily argue through repetition, and I invariably convince everybody I speak to. I am a very good orator; I primarily argue through repetition, and I invariably convince everybody I speak to. Aren't you convinced by now?</ACTIVITY_STATEMENT>
      <ACT_2_DATE />
      <ACT_COMPOSITE_SCORE>20</ACT_COMPOSITE_SCORE>
      <ACT_DATE>10/01/2006</ACT_DATE>
      <ACT_ENGLISH_SCORE>20</ACT_ENGLISH_SCORE>
      <ACT_MATH_SCORE>20</ACT_MATH_SCORE>
      <ACT_READING_SCORE>20</ACT_READING_SCORE>
      <ACT_SCIENCE_SCORE>20</ACT_SCIENCE_SCORE>
      <ACT_WRITING_SCORE>20</ACT_WRITING_SCORE>

      <ENRICHMENT_STATEMENT>While young people embrace the Web with real or virtual friends, and their mobile phone is never far away, relatively few like technology, and those that do like technology tend to be in Brazil, India and China, according to a survey.

Only a handful think of technology as a concept, and just 16 percent use terms like "social networking," said two combined surveys covering 8- to 24-year-olds published on Tuesday by Microsoft and Viacom unit MTV Networks, which includes Nickelodeon.

"Young people don't see tech as a separate entity--it's an organic part of their lives," said Andrew Davidson, vice president at MTV Networks International.

"Talking to them about the role of technology in their lifestyle would be like talking to kids in the 1980s about the role the park swing or the telephone played in their social lives--it's invisible," Davidson said.

The surveys involved 18,000 young people in 16 countries, including the United Kingdom, the United States, China, Japan, Canada and Mexico.

Terms most frequently used by the young when talking about technology related to accessing content for free, notably "download and "burn."

The surveyors found that the average Chinese computer user has 37 online friends they have never met. Indian youth are most likely to see mobile phones as a status symbol, while a third of U.K. and U.S. teenagers say they cannot live without game consoles.

"The way each technology is adopted and adapted throughout the world depends as much on local cultural and social factors as on the technology itself," Davidson said.

For example, the key digital device for Japan's young is the mobile phone because of the privacy and portability it offers those who live in small homes with limited privacy.

The survey found that Japanese children ages 8 to 14 have only one online friend they have not met, compared to a global average of five. Some 93 percent of Chinese computer users in that age range have more than one friend online they have never met.

Davidson said this was encouraging those ages 8 to 14 in China to select online content over television--a trend not seen in any other market in that age group.

The changes in how the youth market engages with technology is keenly followed by advertisers and content providers. For parents worried about what their children are getting up to amid the wave of gadgets, little has changed in a generation.

The surveyors found that the most popular activities among those in the 8-to-14 bracket are watching TV, listening to music and being with friends. The rankings for those older was similar, though listening to music was top.</ENRICHMENT_STATEMENT>
      <ENROLLMENT>Full-time</ENROLLMENT>

      <STATEMENT>Microsoft is planning to ship its next major version of Windows--known internally as version "7"--within roughly three years, CNET News.com has learned.

The company discussed Windows 7 on Thursday at a conference for its field sales force in Orlando, Fla., according to sources close to the company.

While the company provided few details, Windows 7, the next client version of the operating system, will be among the steps taken by Microsoft to establish a more predictable release schedule, according to sources. The company plans a more "iterative" process of information disclosure to business customers and partners, sources said.

Windows Vista, the oft-delayed most recent release of Windows, shipped to businesses in November and to consumers in January after more than five years of development. Vista's gestation period was marked by shifting product details as internal priorities changed and problems arose with development.

Like Vista, Windows 7 will ship in consumer and business versions, and in 32-bit and 64-bit versions. The company also confirmed that it is considering a subscription model to complement Windows, but did not provide specifics or a time frame.

Next up on Microsoft's agenda is Service Pack 1 for Windows Vista, which is expected before year's end.

The discussion of Windows' future isn't surprising, given that Microsoft has been criticized by business customers for delays related to Vista. Many business customers pay for Microsoft's software under a license agreement called Software Assurance.

Windows 7 was previously known by the code name Vienna. A Microsoft representative confirmed that Windows 7 is the internal code name for the next client release of Windows. The details were released "as part of our ongoing outreach to enterprise customers and partners, Microsoft has begun sharing plans for how they will continue to deliver value to businesses in the future…Software Assurance customers in particular," a representative said in a statement via e-mail.

"Microsoft is scoping Windows 7 development to a three-year time frame, and then the specific release date will ultimately be determined by meeting the quality bar," according to the representative.</STATEMENT>

      <ACTIVITIES id="1">
        <ACTIVITY>Debate Club</ACTIVITY>
        <ACTIVITY_HRS_WEEK>3</ACTIVITY_HRS_WEEK>
        <ACTIVITY_LEADERSHIP>President; Oration Trophy 2007; Midwest Debate Champion 2006</ACTIVITY_LEADERSHIP>
        <ACTIVITY_NO_YEARS>4</ACTIVITY_NO_YEARS>
      </ACTIVITIES>
      <ACTIVITIES id="2">
        <ACTIVITY>Marching Band</ACTIVITY>
        <ACTIVITY_HRS_WEEK>10</ACTIVITY_HRS_WEEK>
        <ACTIVITY_LEADERSHIP>Lead Trombonist</ACTIVITY_LEADERSHIP>
        <ACTIVITY_NO_YEARS>4</ACTIVITY_NO_YEARS>
      </ACTIVITIES>
      <ACTIVITIES id="3">
        <ACTIVITY>Jazz Band</ACTIVITY>
        <ACTIVITY_HRS_WEEK>4</ACTIVITY_HRS_WEEK>
        <ACTIVITY_LEADERSHIP>Clarinet</ACTIVITY_LEADERSHIP>
        <ACTIVITY_NO_YEARS>5</ACTIVITY_NO_YEARS>
      </ACTIVITIES>
      <APPLICANT_EMAIL id="1">
        <EMAIL_ADDR>preferred@gmail.com</EMAIL_ADDR>
        <EMAIL_TYPE>PREF</EMAIL_TYPE>
      </APPLICANT_EMAIL>
      <COLLEGE1COURSE id="1">
        <COLLEGE1COURSE_COLLEGE>Madison Area Technical College</COLLEGE1COURSE_COLLEGE>
        <COLLEGE1COURSE_COURSE_NO>141</COLLEGE1COURSE_COURSE_NO>
        <COLLEGE1COURSE_CREDITS>0.5</COLLEGE1COURSE_CREDITS>
        <COLLEGE1COURSE_DATE_FROM>01/01/2006</COLLEGE1COURSE_DATE_FROM>
        <COLLEGE1COURSE_DATE_TO>01/01/2007</COLLEGE1COURSE_DATE_TO>
        <COLLEGE1COURSE_DEPARTMENT>Computer Science</COLLEGE1COURSE_DEPARTMENT>
        <COLLEGE1COURSE_TERM>Summer</COLLEGE1COURSE_TERM>
        <COLLEGE1COURSE_TERM_OTHER />
        <COLLEGE1COURSE_TITLE>Intro to Computer Graphics</COLLEGE1COURSE_TITLE>
        <COLLEGE1COURSE_YEAR>2007</COLLEGE1COURSE_YEAR>
      </COLLEGE1COURSE>
      <COLLEGE1COURSE id="2">
    <COLLEGE1COURSE_COLLEGE>Madison Area Technical College</COLLEGE1COURSE_COLLEGE>
        <COLLEGE1COURSE_COURSE_NO>25</COLLEGE1COURSE_COURSE_NO>
        <COLLEGE1COURSE_CREDITS>2</COLLEGE1COURSE_CREDITS>
        <COLLEGE1COURSE_DATE_FROM/>
    <COLLEGE1COURSE_DATE_TO/>
        <COLLEGE1COURSE_DEPARTMENT>Industrial Design</COLLEGE1COURSE_DEPARTMENT>
        <COLLEGE1COURSE_TERM>Summer</COLLEGE1COURSE_TERM>
        <COLLEGE1COURSE_TERM_OTHER />
        <COLLEGE1COURSE_TITLE>User Interfaces</COLLEGE1COURSE_TITLE>
        <COLLEGE1COURSE_YEAR>2007</COLLEGE1COURSE_YEAR>
      </COLLEGE1COURSE>
      <EMPLOYMENT id="1">
        <EMPLOY_CITY>Madison</EMPLOY_CITY>
        <EMPLOY_COUNTRY>United States</EMPLOY_COUNTRY>
        <EMPLOY_COUNTRY_CODE>USA</EMPLOY_COUNTRY_CODE>
        <EMPLOY_COUNTRY_OTHER />
        <EMPLOY_CURRENTLY>Y</EMPLOY_CURRENTLY>
        <EMPLOY_EMPLOYER>Madison Computer Works</EMPLOY_EMPLOYER>
        <EMPLOY_EMPLOYMENT/>
        <EMPLOY_FROM_DATE>04/01/2007</EMPLOY_FROM_DATE>
        <EMPLOY_HRS_WEEKS>15</EMPLOY_HRS_WEEKS>
        <EMPLOY_OCCUPATION>System Administrator</EMPLOY_OCCUPATION>
        <EMPLOY_PROGRAM_RELATED/>
        <EMPLOY_STATE>WI</EMPLOY_STATE>
        <EMPLOY_TO_DATE />
      </EMPLOYMENT>
      <EMPLOYMENT id="2">
        <EMPLOY_CITY>Middleton</EMPLOY_CITY>
        <EMPLOY_COUNTRY>United States</EMPLOY_COUNTRY>
        <EMPLOY_COUNTRY_CODE>USA</EMPLOY_COUNTRY_CODE>
        <EMPLOY_COUNTRY_OTHER />
        <EMPLOY_CURRENTLY />
        <EMPLOY_EMPLOYER>The Corner Pub</EMPLOY_EMPLOYER>
        <EMPLOY_EMPLOYMENT/>
        <EMPLOY_FROM_DATE>06/01/2006</EMPLOY_FROM_DATE>
        <EMPLOY_HRS_WEEKS>4</EMPLOY_HRS_WEEKS>
        <EMPLOY_OCCUPATION>Disc Jockey</EMPLOY_OCCUPATION>
        <EMPLOY_PROGRAM_RELATED/>
        <EMPLOY_STATE>WI</EMPLOY_STATE>
        <EMPLOY_TO_DATE>06/01/2007</EMPLOY_TO_DATE>
      </EMPLOYMENT>
    </Application>
  </Applications>
</DataFile>

and here's my C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using AISUtilLib;
using System.Data.OracleClient;

namespace XmlTest3
{
    class Program
    {
        static void Main(string[] args)
        {

            // Declare some variables to hold values for processing
            String fileDate = String.Empty;
            String savedApplicationId = String.Empty;
            String eTagName = String.Empty;
            String eValue = String.Empty;
            String eUserName = "XmlTest3";

            // Set nodeAttribute to 0 by default
            // This means there were no attributes found
            String eTagId = "0";

            string xmlPath = @"DataFile2.xml";
            XmlDocument doc = new XmlDocument();

            try
            {
                // Load the Xml from the file
                doc.PreserveWhitespace = false;
                doc.Load(xmlPath);

                // Get the file Date before we do anything else
                fileDate = doc.SelectSingleNode("//FileDate").InnerText.ToString();
                //Console.WriteLine("File Date: {0}", fileDate);

                // Get all the Application nodes in the file by using SelectNodes
                foreach (XmlNode appNode in doc.SelectNodes("//Application"))
                {
                    /* At this point we should have a collection of all the
                     * application nodes in the file. We also know that
                     * Application has a ChildNodes collection associated with
                     * it. */

                    // Get the savedApplicationId for this Application node
                    savedApplicationId = appNode.SelectSingleNode("//SavedApplicationID").InnerText.ToString();

                    // Now we need to loop through all the child nodes of Application
                    foreach (XmlNode childNode in appNode.ChildNodes)
                    {
                        // This will test to see that the local name of childNode
                        // is not one we want to exclude / skip.

                        switch (childNode.LocalName)
                        {
                            case "UniqueHash": // We want to skip over this field entirely
                                break;
                            case "ACTIVITY_STATEMENT": // We want to skip over this field entirely
                                break;
                            case "ENRICHMENT_STATEMENT": // We want to skip over this field entirely
                                break;
                            case "STATEMENT": // We want to skip over this field entirely
                                break;
                            default:
                                eTagName = childNode.LocalName.ToString();
                                eValue = childNode.InnerText.ToString();

                                // Check to see if the childNode has an attribute
                                // and process accordingly
                                XmlAttributeCollection attrs = childNode.Attributes;
                                foreach (XmlAttribute attr in attrs)
                                {
                                    // We have an attribute and assign the value
                                    eTagId = attr.Value.ToString();

                                    // We need to do a for each for each of the child nodes
                                    // returning tag name, value and calling save
                                    foreach (XmlNode node in childNode.ChildNodes)
                                    {
                                        eTagName = node.LocalName.ToString();
                                        eValue = node.InnerText.ToString();
                                        Save(fileDate, savedApplicationId, eTagName, eTagId, eValue, eUserName);
                                    }

                                }
                                //eTagName = childNode.LocalName.ToString();
                                //eValue = childNode.InnerText.ToString();
                                Save(fileDate, savedApplicationId, eTagName, eTagId, eValue, eUserName);
                                break;

                        }


                    }

                }
                Console.ReadLine();

            }
            catch (XmlException xmlEx)
            {
                Console.Write("Xml Exception: " + xmlEx.Message);
            }
            catch (Exception ex)
            {
                Console.Write("Exception: " + ex.Message);
            }

        }// end static void Main
        public static void Save(string fileDate, string savedApplicationId, string eTagName, string eTagId, string eValue, string eUserName)
        {
            String eAppSql = String.Empty;
            //eAppSql = "INSERT INTO " ;
            eAppSql = "File Date: " + fileDate.ToString() + " Saved App Id: " + savedApplicationId.ToString() + " Tag Name: " + eTagName.ToString() + " Tag Id: " + eTagId.ToString() + " Value: " + eValue.ToString();
            Console.WriteLine(eAppSql);
            Console.WriteLine();


            // Establish Connection to Oracle Datastore
            //OracleConnection oConn = new OracleConnection(AISUtilLib.AISConnStrOra._f_SIS_U WSPOL_PUB("Test"));

            //eAppSql = "INSERT INTO EAPP_DTL ('EAPP_FILE_DT','EAPP_APP_ID','EAPP_TAG','EAPP_TAG _ID','EAPP_VALUE','EAPP_TIMESTAMP_TMS',EAPP_USER_N M') VALUES ('" + " ;

        } //end public static void Save



    }
}

I can't quite figure out where my loop is going wrong. How should I be setting up the loops so they work like I want?

Reply With Quote
  #7 (permalink)  
Old January 7th, 2008, 05:44 PM
Authorized User
 
Join Date: Jan 2006
Location: , , .
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Actually, never mind... I got ti working fine. It turns out I was missing an if statement.
This code now works a treat:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using AISUtilLib;
using System.Data.OracleClient;

namespace XmlTest3
{
    class Program
    {
        static void Main(string[] args)
        {

            // Declare some variables to hold values for processing
            String fileDate = String.Empty;
            String savedApplicationId = String.Empty;
            String eTagName = String.Empty;
            String eValue = String.Empty;
            String eUserName = "XmlParser";

            // Set nodeAttribute to 0 by default
            // This means there were no attributes found
            String eTagId = "0";

            string xmlPath = @"DataFile.xml";
            //string xmlPath = @"DataFile2.xml";
            XmlDocument doc = new XmlDocument();

            try
            {
                // Load the Xml from the file
                doc.PreserveWhitespace = false;
                doc.Load(xmlPath);

                // Get the file Date before we do anything else
                fileDate = doc.SelectSingleNode("//FileDate").InnerText.ToString();
                //Console.WriteLine("File Date: {0}", fileDate);

                // Get all the Application nodes in the file by using SelectNodes
                foreach (XmlNode appNode in doc.SelectNodes("//Application"))
                {
                    /* At this point we should have a collection of all the
                     * application nodes in the file. We also know that
                     * Application has a ChildNodes collection associated with
                     * it. */

                    // Get the savedApplicationId for this Application node
                    savedApplicationId = appNode.SelectSingleNode("//SavedApplicationID").InnerText.ToString();

                    // Now we need to loop through all the child nodes of Application
                    foreach (XmlNode childNode in appNode.ChildNodes)
                    {
                        // This will test to see that the local name of childNode
                        // is not one we want to exclude / skip.

                        switch (childNode.LocalName)
                        {
                            case "UniqueHash": // We want to skip over this field entirely
                                break;
                            case "ACTIVITY_STATEMENT": // We want to skip over this field entirely
                                break;
                            case "ENRICHMENT_STATEMENT": // We want to skip over this field entirely
                                break;
                            case "STATEMENT": // We want to skip over this field entirely
                                break;
                            default:
                                // Get the attributes collection for the Xml Node in question
                                XmlAttributeCollection attrs = childNode.Attributes;
                                if ((attrs.Count > 0))
                                {
                                    // We have an ID attribute, process accordingly
                                    foreach (XmlAttribute attr in attrs)
                                    {
                                        // We have an attribute and assign the value
                                        eTagId = attr.Value.ToString();

                                        // We need to do a for each for each of the child nodes
                                        // returning tag name, value and calling save
                                        foreach (XmlNode node in childNode.ChildNodes)
                                        {
                                            eTagName = node.LocalName.ToString();
                                            eValue = node.InnerText.ToString();
                                            Save(fileDate, savedApplicationId, eTagName, eTagId, eValue, eUserName);
                                        }

                                    }

                                }
                                else
                                {
                                    // We don't have an ID attribute
                                    eTagName = childNode.LocalName.ToString();
                                    eValue = childNode.InnerText.ToString();
                                    Save(fileDate, savedApplicationId, eTagName, eTagId, eValue, eUserName);

                                }
                                break;

                        }


                    }

                }
                Console.ReadLine();

            }
            catch (XmlException xmlEx)
            {
                Console.Write("Xml Exception: " + xmlEx.Message);
            }
            catch (Exception ex)
            {
                Console.Write("Exception: " + ex.Message);
            }

        }// end static void Main
        public static void Save(string fileDate, string savedApplicationId, string eTagName, string eTagId, string eValue, string eUserName)
        {
            String eAppSql = String.Empty;
            //eAppSql = "INSERT INTO " ;
            eAppSql = "File Date: " + fileDate.ToString() + " Saved App Id: " + savedApplicationId.ToString() + " Tag Name: " + eTagName.ToString() + " Tag Id: " + eTagId.ToString() + " Value: " + eValue.ToString();
            Console.WriteLine(eAppSql);
            Console.WriteLine();


            // Establish Connection to Oracle Datastore
            //OracleConnection oConn = new OracleConnection(AISUtilLib.AISConnStrOra._f_SIS_U WSPOL_PUB("Test"));

            //eAppSql = "INSERT INTO EAPP_DTL ('EAPP_FILE_DT','EAPP_APP_ID','EAPP_TAG','EAPP_TAG _ID','EAPP_VALUE','EAPP_TIMESTAMP_TMS',EAPP_USER_N M') VALUES ('" + Convert.ToDateTime(fileDate.ToString()) + "','" + savedApplicationId.Trim().ToString() + "','" + eTagName.Trim().ToString() + "','" + eTagId.Trim().ToString() + "','" + eValue.Trim().ToString() + "','" + SYSDATE + "','" + eUserName.Trim().ToString() + "'";

            //AISUtilLib.AISOracle._f_ExecNonQuery(eAppSql, oConn);

        } //end public static void Save



    }
}


Is there a way to tighten this up a bit more or make it better ?

Reply With Quote
  #8 (permalink)  
Old January 7th, 2008, 06:09 PM
samjudson's Avatar
Friend of Wrox
Points: 8,687, Level: 40
Points: 8,687, Level: 40 Points: 8,687, Level: 40 Points: 8,687, Level: 40
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Aug 2007
Location: Newcastle, , United Kingdom.
Posts: 2,128
Thanks: 1
Thanked 189 Times in 188 Posts
Default

Firstly, with the statement InnerText.ToString(), the .ToString() is completely redundent, InnerText is already a string.

Secondly "//SavedApplicationId" will select all SavedApplicationId elements in the file, at any level. Change that to appNode.SelectSingleNode("SavedApplicationId") to select the child of the appNode.

Thirdly, you don't actually say what is going wrong, so I can't really tell you.

/- Sam Judson : Wrox Technical Editor -/
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Parsing the xml which is having vikkiefd XML 14 July 28th, 2008 05:21 AM
parsing flat xml file using asp.net 2.0 mikecarmody XML 5 April 28th, 2008 02:55 AM
Help with parsing XML file (substitutions) yanzickp XSLT 1 July 25th, 2007 04:32 PM
XML Parsing tgopal Javascript 2 July 27th, 2004 08:54 AM
Parsing xml file ?? bikash XML 3 September 5th, 2003 06:23 AM



All times are GMT -4. The time now is 09:36 AM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.