473,503 Members | 972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# reading XML?

11 New Member
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 8237
mwalts
38 New Member
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 New Member
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
blackjack2150
79 New Member
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 New Member
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 New Member
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 New Member
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 New Member
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 New Member
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
blackjack2150
79 New Member
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 New Member
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 New Member
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
3565
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
2382
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
3040
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
2717
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
10273
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
9806
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
3747
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
9496
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
5487
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
3245
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
7282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6995
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7463
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
4678
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3168
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3157
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1515
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
738
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
389
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.