C# reading XML?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • FLX
    New Member
    • May 2007
    • 11

    C# reading XML?

    Hello,

    I'm a beginner and i got serious issues with reading xml in C#.
    This is my XML doc:

    Code:
    <?xml version='1.0' encoding='ISO-8859-1'?><MediaInfo><File CompleteFileName='ToDo'>
    
    <StreamKind ID='General'>
    
    <Stream ID='0'><Tag ID='Format/String'>AVI</Tag>
    
    <Tag ID='OveralBitRate/String'></Tag>
    
    <Tag ID='FileSize/String'>698 MiB</Tag>
    
    </Stream>
    
    </StreamKind>
    
    <StreamKind ID='Video'>
    
    <Stream ID='0'><Tag ID='Codec/String'>XviD</Tag>
    
    <Tag ID='Width'>640</Tag>
    
    <Tag ID='Height'>272</Tag>
    
    </Stream>
    
    </StreamKind>
    
    <StreamKind ID='Audio'>
    
    <Stream ID='0'><Tag ID='Codec/String'>AC3</Tag>
    
    <Tag ID='SamplingRate/String'>48 KHz</Tag>
    
    </Stream>
    
    </StreamKind>
    
    </File>
    
    </MediaInfo>
    I'm trying to fetch the Width, Height and SamplingRate/String into textboxes.
    I started with the width, and i came up with this:

    Code:
            XmlDocument doc = new XmlDocument();
            doc.Load("C:\\example.xml");
            xmlwidth = doc.GetElementById("Width");
            newWidthBox.Text = xmlwidth;
    I just cant get it to work, can somebody give me advice?
    Thanks in advance!

    Regards,

    Dennis
  • mwalts
    New Member
    • May 2007
    • 38

    #2
    Originally posted by FLX
    Hello,

    I'm a beginner and i got serious issues with reading xml in C#.
    This is my XML doc:

    Code:
    <?xml version='1.0' encoding='ISO-8859-1'?><MediaInfo><File CompleteFileName='ToDo'>
    
    <StreamKind ID='General'>
    
    <Stream ID='0'><Tag ID='Format/String'>AVI</Tag>
    
    <Tag ID='OveralBitRate/String'></Tag>
    
    <Tag ID='FileSize/String'>698 MiB</Tag>
    
    </Stream>
    
    </StreamKind>
    
    <StreamKind ID='Video'>
    
    <Stream ID='0'><Tag ID='Codec/String'>XviD</Tag>
    
    <Tag ID='Width'>640</Tag>
    
    <Tag ID='Height'>272</Tag>
    
    </Stream>
    
    </StreamKind>
    
    <StreamKind ID='Audio'>
    
    <Stream ID='0'><Tag ID='Codec/String'>AC3</Tag>
    
    <Tag ID='SamplingRate/String'>48 KHz</Tag>
    
    </Stream>
    
    </StreamKind>
    
    </File>
    
    </MediaInfo>
    I'm trying to fetch the Width, Height and SamplingRate/String into textboxes.
    I started with the width, and i came up with this:

    Code:
            XmlDocument doc = new XmlDocument();
            doc.Load("C:\\example.xml");
            xmlwidth = doc.GetElementById("Width");
            newWidthBox.Text = xmlwidth;
    I just cant get it to work, can somebody give me advice?
    Thanks in advance!

    Regards,

    Dennis
    Well for starters, GetElementByID returns a XmlElement not a string so try something more like this

    Code:
            XmlDocument doc = new XmlDocument();
            doc.Load("C:\\example.xml");
            XmlElement xmlwidth = doc.GetElementById("Width");
            newWidthBox.Text = xmlwidth.InnerText;
    You might also want to look into SelectNodes and SelectSingleNod e (along with the XPath syntax they both follow) if you find that GetElementById isn't doing what you want

    Good luck,

    -mwalts

    Comment

    • FLX
      New Member
      • May 2007
      • 11

      #3
      Dear mwalts,

      First of all, thanks for your swift reply, its highly appreciated.
      The code that you have posted unfortunately doesnt work. JIT debug catches errors at line 36, which is the "newWidthBox.Te xt = xmlwidth.InnerT ext;" line.
      Does anyone know what is wrong with it?

      Regards,

      Dennis

      Comment

      • blackjack2150
        New Member
        • Feb 2007
        • 79

        #4
        Originally posted by FLX
        Dear mwalts,

        First of all, thanks for your swift reply, its highly appreciated.
        The code that you have posted unfortunately doesnt work. JIT debug catches errors at line 36, which is the "newWidthBox.Te xt = xmlwidth.InnerT ext;" line.
        Does anyone know what is wrong with it?

        Regards,

        Dennis
        What's the error message? Is the xmlwidth object null/empty?
        If I were you I would use SelectNode or SelectSingleNod e methods to fetch the values from the XML file. These, however require usage of XPath. But in your case the file is very small, so the expression won't be too complex. I would suggest you read the tutorial on w3schools.com about XPath.

        All the best!

        Comment

        • FLX
          New Member
          • May 2007
          • 11

          #5
          hello all,

          the error that JIT spits out is "System.NullRef erenceException : Object reference not set to an instance of an object.". I also looked up xpath, but i cant find a good example of extracting a single value, can anyone help me with that?

          Regards,

          Dennis

          Comment

          • mwalts
            New Member
            • May 2007
            • 38

            #6
            Originally posted by FLX
            hello all,

            the error that JIT spits out is "System.NullRef erenceException : Object reference not set to an instance of an object.". I also looked up xpath, but i cant find a good example of extracting a single value, can anyone help me with that?

            Regards,

            Dennis
            Ok, so it's obvious that the GetElementById is not doing what you want.

            From your example it seemed right to me, but I admit I don't often use that method. As for XPath, try looking through this (yes, the whole thing)
            http://www.w3schools.c om/xpath/xpath_intro.asp

            Looks like your xPath expression would be something like this:
            /MediaInfo/File/StreamKind/Stream/Tag[@ID='Width']

            Throw that into a SelectSingleNod e and it should do it.

            You should still test for a null response and handle it accordingly though. And remember XML is case sensitive so if any of the nodes above are spelled incorrectly, it won't work.

            If your trying to get everything from the video node though, you might want to try something more like this

            Code:
                          XmlDocument doc = new XmlDocument();
                          doc.Load("C:\\example.xml");
                          XmlNode VidNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Video'];
                          //Do all the stuff we want now on VidNode instead, notice that an
                          //XmlNode still has SelectSingleNode and SelectNodes methods
                          //To find width from here it would be like
                          XmlNode widthNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Width']");
                          //Now use the widthNode.InnerText to get the width you wanted
            Good luck,

            -mwalts

            Comment

            • FLX
              New Member
              • May 2007
              • 11

              #7
              Originally posted by mwalts
              Ok, so it's obvious that the GetElementById is not doing what you want.

              From your example it seemed right to me, but I admit I don't often use that method. As for XPath, try looking through this (yes, the whole thing)
              http://www.w3schools.c om/xpath/xpath_intro.asp

              Looks like your xPath expression would be something like this:
              /MediaInfo/File/StreamKind/Stream/Tag[@ID='Width']

              Throw that into a SelectSingleNod e and it should do it.

              You should still test for a null response and handle it accordingly though. And remember XML is case sensitive so if any of the nodes above are spelled incorrectly, it won't work.

              If your trying to get everything from the video node though, you might want to try something more like this

              Code:
                            XmlDocument doc = new XmlDocument();
                            doc.Load("C:\\example.xml");
                            XmlNode VidNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Video'];
                            //Do all the stuff we want now on VidNode instead, notice that an
                            //XmlNode still has SelectSingleNode and SelectNodes methods
                            //To find width from here it would be like
                            XmlNode widthNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Width']");
                            //Now use the widthNode.InnerText to get the width you wanted
              Good luck,

              -mwalts
              Awesome man, you made my day! there was a slight error in VidNode tho, it needed to be:
              Code:
              XmlNode VidNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Video']");
              Thanks so much :D

              Regards,

              Dennis

              Comment

              • mwalts
                New Member
                • May 2007
                • 38

                #8
                Originally posted by FLX
                Awesome man, you made my day! there was a slight error in VidNode tho, it needed to be:
                Code:
                XmlNode VidNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Video']");
                Thanks so much :D

                Regards,

                Dennis
                Yeah, it did it directly in this silly little post window, so no surprise it wasn't perfect :p

                Glad it helped,

                -mwalts

                Comment

                • FLX
                  New Member
                  • May 2007
                  • 11

                  #9
                  Hello again,

                  I have the feeling that there still is something wrong with the code.
                  JIT gives the following error:
                  Code:
                  ************** Exception Text **************
                  System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
                     at System.Xml.XmlTextReaderImpl.Throw(Exception e)
                     at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
                     at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
                     at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
                     at System.Xml.XmlTextReaderImpl.Read()
                     at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
                     at System.Xml.XmlDocument.Load(XmlReader reader)
                     at System.Xml.XmlDocument.LoadXml(String xml)
                     at ZunEnc.Form1.encodeButton_Click(Object sender, EventArgs e) in C:\Users\FLX\Documents\Visual Studio 2005\Projects\ZunEnc\ZunEnc\Form1.cs:line 42
                     at System.Windows.Forms.Control.OnClick(EventArgs e)
                     at System.Windows.Forms.Button.OnClick(EventArgs e)
                     at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
                     at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
                     at System.Windows.Forms.Control.WndProc(Message& m)
                     at System.Windows.Forms.ButtonBase.WndProc(Message& m)
                     at System.Windows.Forms.Button.WndProc(Message& m)
                     at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
                     at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
                     at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
                  I use the following code:
                  Code:
                              //start grabbing XML values from mediainfo
                              XmlDocument doc = new XmlDocument();
                              //grabs xml from string
                              doc.LoadXml(outputMediaInfo);
                              //defining nodes to grab
                              XmlNode VidNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Video']");
                              XmlNode AudioNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Audio']");
                              //grabbing the values
                              XmlNode samplingNode = AudioNode.SelectSingleNode("Stream/Tag[@ID='SamplingRate/String']");
                              XmlNode audioCodecNode = AudioNode.SelectSingleNode("Stream/Tag[@ID='Codec/String']");
                              XmlNode widthNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Width']");
                              XmlNode heightNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Height']");
                              //putting the values in their designated boxes
                              widthBox.Text = widthNode.InnerText;
                              heightBox.Text = heightNode.InnerText;
                              audioCodecBox.Text = audioCodecNode.InnerText;
                              audioSamplingBox.Text = samplingNode.InnerText;
                              //end grabbing xml from mediainfo
                  I did a lot of research on the web, but i cant find out whats causing this.
                  Can someone help me?

                  Thanks so much!

                  Regards,

                  Dennis

                  Comment

                  • blackjack2150
                    New Member
                    • Feb 2007
                    • 79

                    #10
                    I usually do something like this:

                    XmlNode nd = doc.DocumentElement.SelectSingleNo de(..);

                    ,where doc is the XmlDocument. The DocumentElement property returns the root element, so you don't bother with it anymore in your XPath expression.

                    Comment

                    • mwalts
                      New Member
                      • May 2007
                      • 38

                      #11
                      Originally posted by FLX
                      Hello again,

                      I have the feeling that there still is something wrong with the code.
                      JIT gives the following error:
                      Code:
                      ************** Exception Text **************
                      System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
                         at System.Xml.XmlTextReaderImpl.Throw(Exception e)
                         at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
                         at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
                         at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
                         at System.Xml.XmlTextReaderImpl.Read()
                         at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
                         at System.Xml.XmlDocument.Load(XmlReader reader)
                         at System.Xml.XmlDocument.LoadXml(String xml)
                         at ZunEnc.Form1.encodeButton_Click(Object sender, EventArgs e) in C:\Users\FLX\Documents\Visual Studio 2005\Projects\ZunEnc\ZunEnc\Form1.cs:line 42
                         at System.Windows.Forms.Control.OnClick(EventArgs e)
                         at System.Windows.Forms.Button.OnClick(EventArgs e)
                         at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
                         at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
                         at System.Windows.Forms.Control.WndProc(Message& m)
                         at System.Windows.Forms.ButtonBase.WndProc(Message& m)
                         at System.Windows.Forms.Button.WndProc(Message& m)
                         at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
                         at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
                         at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
                      I use the following code:
                      Code:
                                  //start grabbing XML values from mediainfo
                                  XmlDocument doc = new XmlDocument();
                                  //grabs xml from string
                                  doc.LoadXml(outputMediaInfo);
                                  //defining nodes to grab
                                  XmlNode VidNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Video']");
                                  XmlNode AudioNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Audio']");
                                  //grabbing the values
                                  XmlNode samplingNode = AudioNode.SelectSingleNode("Stream/Tag[@ID='SamplingRate/String']");
                                  XmlNode audioCodecNode = AudioNode.SelectSingleNode("Stream/Tag[@ID='Codec/String']");
                                  XmlNode widthNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Width']");
                                  XmlNode heightNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Height']");
                                  //putting the values in their designated boxes
                                  widthBox.Text = widthNode.InnerText;
                                  heightBox.Text = heightNode.InnerText;
                                  audioCodecBox.Text = audioCodecNode.InnerText;
                                  audioSamplingBox.Text = samplingNode.InnerText;
                                  //end grabbing xml from mediainfo
                      I did a lot of research on the web, but i cant find out whats causing this.
                      Can someone help me?

                      Thanks so much!

                      Regards,

                      Dennis
                      So, it's doing this on the doc.Load? it looks like your XML is probably "Not well formed"

                      You can look at the w3c school site to figure out exactly what is wrong, but in general it could be that a tag doesn't have a matching terminator (and remember, it is case sensitive) or an invalid character is included somewhere (there are a lot of them). If it's the character issue, you'll want to look into CData sections.

                      If you post the XML file contents here, someone might be able to help you. If it's too big, save a copy, cut it back, try it out, and if the same problem occurs, post that snippet

                      Have fun,

                      -mwalts

                      Comment

                      • FLX
                        New Member
                        • May 2007
                        • 11

                        #12
                        I think its because the xml file is formed by an external application, and it doesnt have a wait on it, so it already starts grabbing while its still compiling.

                        Comment

                        Working...