473,231 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,231 software developers and data experts.

C# reading XML?

11
Hello,

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

Expand|Select|Wrap|Line Numbers
  1. <?xml version='1.0' encoding='ISO-8859-1'?><MediaInfo><File CompleteFileName='ToDo'>
  2.  
  3. <StreamKind ID='General'>
  4.  
  5. <Stream ID='0'><Tag ID='Format/String'>AVI</Tag>
  6.  
  7. <Tag ID='OveralBitRate/String'></Tag>
  8.  
  9. <Tag ID='FileSize/String'>698 MiB</Tag>
  10.  
  11. </Stream>
  12.  
  13. </StreamKind>
  14.  
  15. <StreamKind ID='Video'>
  16.  
  17. <Stream ID='0'><Tag ID='Codec/String'>XviD</Tag>
  18.  
  19. <Tag ID='Width'>640</Tag>
  20.  
  21. <Tag ID='Height'>272</Tag>
  22.  
  23. </Stream>
  24.  
  25. </StreamKind>
  26.  
  27. <StreamKind ID='Audio'>
  28.  
  29. <Stream ID='0'><Tag ID='Codec/String'>AC3</Tag>
  30.  
  31. <Tag ID='SamplingRate/String'>48 KHz</Tag>
  32.  
  33. </Stream>
  34.  
  35. </StreamKind>
  36.  
  37. </File>
  38.  
  39. </MediaInfo>
  40.  
I'm trying to fetch the Width, Height and SamplingRate/String into textboxes.
I started with the width, and i came up with this:

Expand|Select|Wrap|Line Numbers
  1.         XmlDocument doc = new XmlDocument();
  2.         doc.Load("C:\\example.xml");
  3.         xmlwidth = doc.GetElementById("Width");
  4.         newWidthBox.Text = xmlwidth;
  5.  
I just cant get it to work, can somebody give me advice?
Thanks in advance!

Regards,

Dennis
May 29 '07 #1
11 8219
mwalts
38
Hello,

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

Expand|Select|Wrap|Line Numbers
  1. <?xml version='1.0' encoding='ISO-8859-1'?><MediaInfo><File CompleteFileName='ToDo'>
  2.  
  3. <StreamKind ID='General'>
  4.  
  5. <Stream ID='0'><Tag ID='Format/String'>AVI</Tag>
  6.  
  7. <Tag ID='OveralBitRate/String'></Tag>
  8.  
  9. <Tag ID='FileSize/String'>698 MiB</Tag>
  10.  
  11. </Stream>
  12.  
  13. </StreamKind>
  14.  
  15. <StreamKind ID='Video'>
  16.  
  17. <Stream ID='0'><Tag ID='Codec/String'>XviD</Tag>
  18.  
  19. <Tag ID='Width'>640</Tag>
  20.  
  21. <Tag ID='Height'>272</Tag>
  22.  
  23. </Stream>
  24.  
  25. </StreamKind>
  26.  
  27. <StreamKind ID='Audio'>
  28.  
  29. <Stream ID='0'><Tag ID='Codec/String'>AC3</Tag>
  30.  
  31. <Tag ID='SamplingRate/String'>48 KHz</Tag>
  32.  
  33. </Stream>
  34.  
  35. </StreamKind>
  36.  
  37. </File>
  38.  
  39. </MediaInfo>
  40.  
I'm trying to fetch the Width, Height and SamplingRate/String into textboxes.
I started with the width, and i came up with this:

Expand|Select|Wrap|Line Numbers
  1.         XmlDocument doc = new XmlDocument();
  2.         doc.Load("C:\\example.xml");
  3.         xmlwidth = doc.GetElementById("Width");
  4.         newWidthBox.Text = xmlwidth;
  5.  
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

Expand|Select|Wrap|Line Numbers
  1.         XmlDocument doc = new XmlDocument();
  2.         doc.Load("C:\\example.xml");
  3.         XmlElement xmlwidth = doc.GetElementById("Width");
  4.         newWidthBox.Text = xmlwidth.InnerText;
  5.  
You might also want to look into SelectNodes and SelectSingleNode (along with the XPath syntax they both follow) if you find that GetElementById isn't doing what you want

Good luck,

-mwalts
May 29 '07 #2
FLX
11
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.Text = xmlwidth.InnerText;" line.
Does anyone know what is wrong with it?

Regards,

Dennis
May 29 '07 #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.Text = xmlwidth.InnerText;" 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 SelectSingleNode 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!
May 29 '07 #4
FLX
11
hello all,

the error that JIT spits out is "System.NullReferenceException: 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
May 29 '07 #5
mwalts
38
hello all,

the error that JIT spits out is "System.NullReferenceException: 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.com/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 SelectSingleNode 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

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

-mwalts
May 29 '07 #6
FLX
11
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.com/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 SelectSingleNode 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

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

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

Regards,

Dennis
May 29 '07 #7
mwalts
38
Awesome man, you made my day! there was a slight error in VidNode tho, it needed to be:
Expand|Select|Wrap|Line Numbers
  1. 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
May 29 '07 #8
FLX
11
Hello again,

I have the feeling that there still is something wrong with the code.
JIT gives the following error:
Expand|Select|Wrap|Line Numbers
  1. ************** Exception Text **************
  2. System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
  3.    at System.Xml.XmlTextReaderImpl.Throw(Exception e)
  4.    at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
  5.    at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
  6.    at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
  7.    at System.Xml.XmlTextReaderImpl.Read()
  8.    at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
  9.    at System.Xml.XmlDocument.Load(XmlReader reader)
  10.    at System.Xml.XmlDocument.LoadXml(String xml)
  11.    at ZunEnc.Form1.encodeButton_Click(Object sender, EventArgs e) in C:\Users\FLX\Documents\Visual Studio 2005\Projects\ZunEnc\ZunEnc\Form1.cs:line 42
  12.    at System.Windows.Forms.Control.OnClick(EventArgs e)
  13.    at System.Windows.Forms.Button.OnClick(EventArgs e)
  14.    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
  15.    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
  16.    at System.Windows.Forms.Control.WndProc(Message& m)
  17.    at System.Windows.Forms.ButtonBase.WndProc(Message& m)
  18.    at System.Windows.Forms.Button.WndProc(Message& m)
  19.    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
  20.    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
  21.    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  22.  
I use the following code:
Expand|Select|Wrap|Line Numbers
  1.             //start grabbing XML values from mediainfo
  2.             XmlDocument doc = new XmlDocument();
  3.             //grabs xml from string
  4.             doc.LoadXml(outputMediaInfo);
  5.             //defining nodes to grab
  6.             XmlNode VidNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Video']");
  7.             XmlNode AudioNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Audio']");
  8.             //grabbing the values
  9.             XmlNode samplingNode = AudioNode.SelectSingleNode("Stream/Tag[@ID='SamplingRate/String']");
  10.             XmlNode audioCodecNode = AudioNode.SelectSingleNode("Stream/Tag[@ID='Codec/String']");
  11.             XmlNode widthNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Width']");
  12.             XmlNode heightNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Height']");
  13.             //putting the values in their designated boxes
  14.             widthBox.Text = widthNode.InnerText;
  15.             heightBox.Text = heightNode.InnerText;
  16.             audioCodecBox.Text = audioCodecNode.InnerText;
  17.             audioSamplingBox.Text = samplingNode.InnerText;
  18.             //end grabbing xml from mediainfo
  19.  
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
May 30 '07 #9
I usually do something like this:

XmlNode nd = doc.DocumentElement.SelectSingleNode(..);

,where doc is the XmlDocument. The DocumentElement property returns the root element, so you don't bother with it anymore in your XPath expression.
May 30 '07 #10
mwalts
38
Hello again,

I have the feeling that there still is something wrong with the code.
JIT gives the following error:
Expand|Select|Wrap|Line Numbers
  1. ************** Exception Text **************
  2. System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
  3.    at System.Xml.XmlTextReaderImpl.Throw(Exception e)
  4.    at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
  5.    at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
  6.    at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
  7.    at System.Xml.XmlTextReaderImpl.Read()
  8.    at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
  9.    at System.Xml.XmlDocument.Load(XmlReader reader)
  10.    at System.Xml.XmlDocument.LoadXml(String xml)
  11.    at ZunEnc.Form1.encodeButton_Click(Object sender, EventArgs e) in C:\Users\FLX\Documents\Visual Studio 2005\Projects\ZunEnc\ZunEnc\Form1.cs:line 42
  12.    at System.Windows.Forms.Control.OnClick(EventArgs e)
  13.    at System.Windows.Forms.Button.OnClick(EventArgs e)
  14.    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
  15.    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
  16.    at System.Windows.Forms.Control.WndProc(Message& m)
  17.    at System.Windows.Forms.ButtonBase.WndProc(Message& m)
  18.    at System.Windows.Forms.Button.WndProc(Message& m)
  19.    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
  20.    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
  21.    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  22.  
I use the following code:
Expand|Select|Wrap|Line Numbers
  1.             //start grabbing XML values from mediainfo
  2.             XmlDocument doc = new XmlDocument();
  3.             //grabs xml from string
  4.             doc.LoadXml(outputMediaInfo);
  5.             //defining nodes to grab
  6.             XmlNode VidNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Video']");
  7.             XmlNode AudioNode = doc.SelectSingleNode("/MediaInfo/File/StreamKind[@ID='Audio']");
  8.             //grabbing the values
  9.             XmlNode samplingNode = AudioNode.SelectSingleNode("Stream/Tag[@ID='SamplingRate/String']");
  10.             XmlNode audioCodecNode = AudioNode.SelectSingleNode("Stream/Tag[@ID='Codec/String']");
  11.             XmlNode widthNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Width']");
  12.             XmlNode heightNode = VidNode.SelectSingleNode("Stream/Tag[@ID='Height']");
  13.             //putting the values in their designated boxes
  14.             widthBox.Text = widthNode.InnerText;
  15.             heightBox.Text = heightNode.InnerText;
  16.             audioCodecBox.Text = audioCodecNode.InnerText;
  17.             audioSamplingBox.Text = samplingNode.InnerText;
  18.             //end grabbing xml from mediainfo
  19.  
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
May 30 '07 #11
FLX
11
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.
Jun 4 '07 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Andy | last post by:
Hi, In the code below (not pretty I know but it's an early version :-P) I'm having problems reading the data object back in. If I move the reading code to immediately after the section where it...
6
by: Raymond Hettinger | last post by:
Found in a pamphlet at a pre-school: --------------------------------------- Reading improves vocabulary Reading raises cultural literacy through shared knowledge Reading develops writing skills...
4
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be
24
by: Hendrik Schober | last post by:
Hi, I have a 'std::istream' and need to read its whole contents into a string. How can I do this? TIA; Schobi
19
by: Lionel B | last post by:
Greetings, I need to read (unformatted text) from stdin up to EOF into a char buffer; of course I cannot allocate my buffer until I know how much text is available, and I do not know how much...
4
by: Oliver Knoll | last post by:
According to my ANSI book, tmpfile() creates a file with wb+ mode (that is just writing, right?). How would one reopen it for reading? I got the following (which works): FILE *tmpFile =...
6
by: KevinD | last post by:
assumption: I am new to C and old to COBOL I have been reading a lot (self teaching) but something is not sinking in with respect to reading a simple file - one record at a time. Using C, I am...
3
by: Nick | last post by:
I have found a class that compresses and uncompresses data but need some help with how to use part of it below is the deflate method which compresses the string that I pass in, this works OK. At...
9
by: Mike Reed | last post by:
I must be having a "senile" day! I cannot recall, nor get to work, code to read a cookie's expiration date/time in an ASP page/VBScript. What am I missing? *** Sent via Developersdex...
4
by: Gaijinco | last post by:
I had a file named nap.in which looks like this: 4 10:00 12:00 Lectures 12:00 13:00 Lunch, like always. 13:00 15:00 Boring lectures... 15:30 17:45 Reading 4 10:00 12:00 Lectures 12:00 13:00...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.