Parsing Xml

This is a discussion on Parsing Xml within the C# Programming forums, part of the General Programming Boards category; Hi all Need a bit of help with some XML ( i am new to XML so not sure what ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    85

    Parsing Xml

    Hi all

    Need a bit of help with some XML ( i am new to XML so not sure what i am doing)

    i have used a httprequest to acquire the xml information i need but i believe it uses elements
    note . this is not the file im using just an example.

    <people>
    <location>
    <list name="ben" surname="gunn" location="peru" dwelling="house"/>
    <list name="tom" surname="cruise" location="miami" dweliing="condo"/>
    ...

    </location>
    </people>

    Code:
    XmlTextWriter writer = new XmlTextWriter(Console.Out);
                XmlDocument mydata = new XmlDocument();
                mydata = GetData(xmlUrl); // pass the url for xml stream
                
                XmlNode root = mydata.DocumentElement;
    
                XmlNodeList elemList = root.ChildNodes;
                 IEnumerator ienum = elemList.GetEnumerator();
                 
                while (ienum.MoveNext())
                 {
                     XmlNode title = (XmlNode)ienum.Current;
                     if (title.HasChildNodes)
                     {
                         Console.Write(title.Name + Environment.NewLine);
                         Console.Write(title.FirstChild.Name + Environment.NewLine);
                         Console.Write(title.NodeType); 
    // dont really want the type but the first element i.e its name "name" and contents "ben"
                         
                     }
                     Console.WriteLine(title.OuterXml);
                 }
    so i basically want to be able to find the root, check each child and see if that child has any elements, if it has i want to parse them individually so i can see what the elements are and get their values.

    the above will give me the root and i can compare to see whether it has any child info or not but hiow do i access the elements ?

    i am not 100% with IENumerator but can see it is returning a count of some sort for looping through.

    im sorry if this is vague, but as i said im new to XML at the moment.

    thanks in advance.

  2. #2
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    You could use linq to sql.
    Here to Deceive, Inveigle, Obfuscate Since 1945

  3. #3
    Registered User
    Join Date
    Aug 2008
    Posts
    188
    it's pretty simple you're on the right track.

    based on
    Code:
    <people>
    <location>
    <list name="ben" surname="gunn" location="peru" dwelling="house"/>
    </location>
    </people>
    
    XmlDocument doc; // load with above
    // doc.DocumentElement.Name == "people"
    // doc.DocumentElement.ChildNodes.Count == 1
    // doc.DocumentElement.ChildNodes[0].Name = "location"
    // doc.DocumentElement.ChildNodes[0].ChildNodes.Count == 1
    // doc.DocumentElement.ChildNodes[0].ChildNodes[0].Name == "list"
    // doc.DocumentElement.ChildNodes[0].ChildNodes[0].Attributes.Count == 4
    // doc.DocumentElement.ChildNodes[0].ChildNodes[0].Attributes[0].Name == "name"
    // doc.DocumentElement.ChildNodes[0].ChildNodes[0].Attributes[0].Value == "ben"

  4. #4
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    I personally use xpath for most of my XML reading, but that's only a truly viable option if you know the structure of the XML file in advance. I'd probably use the XmlNode system if I had to parse arbitrary XML documents.

    That is, it's really easy to do something like "I want to find the Resolution attribute under Options\Settings\Video".

    Anyhow, this should work to list attributes:

    Code:
    private void ListAttributes(XmlNode node)
    {
        foreach(XmlAttribute att in node.Attributes)
        {
            Console.Write(att.Name + " = " + att.Value + Environment.NewLine);
        }
    }
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  5. #5
    Registered User
    Join Date
    Oct 2008
    Posts
    85

    Question

    thanks for the help, appreciated.

    i had some time to play around with this today and came up with an alternative to your suggestions which does what i need.

    assuming that the people.xml has been saved to a file.

    XML file :

    <people>
    <location>
    <list name="ben" surname="gunn" location="peru" dwelling="house"/>
    <list name="tom" surname="cruise" location="miami" dweliing="condo"/>
    </location>
    </people>

    Code:
    String fname = "people.xml";
                XmlDocument mypeople = new XmlDocument();
                FileStream Fstream = null;
    
                if (File.Exists(fname))
                {
               
    
                    try
                    {
                        Fstream = new FileStream(fname,
                                                      FileMode.Open,
                                                      FileAccess.Read);
                        // Open the XML file
                        mypeople.Load(Fstream);
                    }
                    finally
                    {
                        Fstream.Close();
                    }
                }
                
                XmlNodeList people = mypeople.GetElementsByTagName("list");
    
                int pad = 10; //pad spacing value
                
                Console.WriteLine(" =-= People=-=");
    
                Console.WriteLine(
                     "Name".PadRight(pad, '-') + 
                     "Surname".PadRight(pad, '-') +
                     "Location".PadRight(pad, '-') + 
                     "Dwelling".PadRight(pad, '-')
                                             );
    
                 foreach (XmlNode attr in people)
                    {
                      Console.WriteLine(
                            "{0} {1} {2} {3}  ",
                            attr.Attributes["name"].InnerText.PadLeft(pad,'-'),
                            attr.Attributes["surname"].InnerText.PadLeft(pad, '-'),
                            attr.Attributes["location"].InnerText.PadLeft(pad,'-'),
                            attr.Attributes["dwelling"].InnerText.PadLeft(pad,'-'),
                                               );
                    
                                }
                     Console.ReadKey();
                    }
    ignore the pad statement was messing with alignment on console. but this does achieve the desired effect.

    just have to get it into a gridview in ASP.net now

    Hope this helps someone else out.

  6. #6
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Oh, if you know the structure of the file and just want to read attributes in that fashion, you can easily do that with XPath.

    Sample:

    Code:
                XPathDocument d = new XPathDocument("people.xml");
                XPathNavigator root = d.CreateNavigator();
    
                XPathNodeIterator listIter = root.Select("/people/location/list");
                while (listIter.MoveNext())
                {
                    string name = listIter.Current.Evaluate("string(@name)") as string;
                    string surname = listIter.Current.Evaluate("string(@surname)") as string;
                    string location = listIter.Current.Evaluate("string(@location)") as string;
                    string dwelling = listIter.Current.Evaluate("string(@dwelling)") as string;
                }
    XPath has a lot more advanced features as well, but this is a simple example.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  7. #7
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,807
    So many ways to do the same thing
    Code:
    XmlDocument peopleXmlDoc = new XmlDocument();
    peopleXmlDoc.load("people.xml");
    
    XmlNodeList peopleList = peopleXmlDoc.DocumentElement.SelectNodes("location/list");
    foreach(XmlNode peopleNode in peopleList)
    {
        string name = peopleNode.Attributes["name"].InnerText;
    }//foreach
    Woop?

  8. #8
    Registered User
    Join Date
    Oct 2008
    Posts
    85
    yes i was fortunate enough to have pulled the file and checked the structure of the XML so i knew what the layout was.

    I t seems to me, after returning to programming after a very log break that it is more about knowing what is available already and using it to its best abilities rather than reinventing the wheel every time.

    It also seems that a lot of classes offer similar yet slightly different ways to do things and a few appear to carry certain limitations to make them viable in some scenarios. Very confusing.

    but as said above

    so many ways to do the same thing !

    the most time consuming part for me is finding a way to do it and finding out theres a better ( easier) way :S

    but even if only one person benefits from posts like this - i think it is worth asking the question
    Last edited by deviousdexter; 04-24-2009 at 06:31 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Parsing XML with C without 3rd party libs
    By mike_morley in forum C Programming
    Replies: 13
    Last Post: 12-18-2008, 01:21 PM
  2. xml file parsing in C
    By lonbgeach in forum Tech Board
    Replies: 31
    Last Post: 12-14-2006, 01:14 AM
  3. XML Parsing
    By Mareq in forum C++ Programming
    Replies: 8
    Last Post: 11-09-2005, 08:20 PM
  4. Parsing XML in C++
    By CompiledMonkey in forum C++ Programming
    Replies: 9
    Last Post: 06-22-2004, 11:37 AM
  5. XML File Parsing
    By WebSnozz in forum C++ Programming
    Replies: 0
    Last Post: 04-21-2002, 03:24 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21