?
Solved

read xml file in C#

Posted on 2014-02-13
7
Medium Priority
?
590 Views
Last Modified: 2014-02-14
Do you see anything wrong in my code? I am trying to read xml file. It does not like my foreach.

public string Get_Config_valuex(string Key_NAME)
        {
            string result;
            XDocument xdoc = new XDocument();
            using (FileStream instream = new FileStream(@"E:\\xmlfile.config", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                 using (StreamReader reader = new StreamReader(instream))
                {
                     xdoc = XDocument.Load(reader); 
                     var ArrResults = from c in xdoc.Descendants("ADD")
                     foreach (XElement Each_Results in ArrResults)
                     {
                      if (Each_Results.Attribute("key") == (Key_NAME.ToUpper))
                            result = Each_Results.Attribute("VALUE").Value;    
                              break;
                     }   
                }
                  
            }
        }

Open in new window

0
Comment
Question by:VBdotnet2005
7 Comments
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 39856829
Hi VBdotnet2005;

First you are most likely getting an exception that states you must have a select or a group clause at the end. Please post the exact exception message and inner exception message that you are receiving. Please also describe what you want the end result to look like and it would help to see what the XML document looks like so please post.

Second you can load the XML document in a less verbose way for example:

XDocument xdoc = XDocument.Load("E:/xmlfile.config");
0
 
LVL 13

Expert Comment

by:Jitendra Patil
ID: 39858458
hi you  can try the below links
How to read XML from a file by using Visual Basic .NET
HOW TO: Read XML Data into a DataSet by Using Visual Basic .NET
OR try the below code
Imports System.Xml
Imports System.Data
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim xmlFile As XmlReader
        xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings())
        Dim ds As New DataSet
        ds.ReadXml(xmlFile)
        Dim i As Integer
        For i = 0 To ds.Tables(0).Rows.Count - 1
            MsgBox(ds.Tables(0).Rows(i).Item(1))
        Next
    End Sub
End Class
hope this helps.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39858574
As Fernando alluded to, you appear to be missing the select clause in your Linq:
var ArrResults = from c in xdoc.Descendants("ADD")
                          select c;

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:VBdotnet2005
ID: 39860124
This is my xml format. I just want it to return value = "mystring"


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appsettings>
    <ADD key ="server1" VALUE="mystring" />
    <ADD key="server2" VALUE="mystring" />
      
      etc...
   
  </appsettings>
</configuration>
0
 
LVL 64

Accepted Solution

by:
Fernando Soto earned 2000 total points
ID: 39860194
Hi VBdotnet2005;

Well then this should work for you.

// Load the xml document into a XDocument node from a file on the system
XDocument xdoc = XDocument.Load("C:/Working Directory/MyConfig.xml");
// Or if the XML is already in memory as a string you can load it this way 
// for example assuming the variable name is myXml
XDocument xdoc = XDocument.Parse(myXml);

// Query for the ADD nodes and return the VALUE attribute for each
var results = from a in xdoc.Descendants("ADD")
              select a.Attribute("VALUE").Value;
              
foreach (string val in results)
{
	  // Write out the value
    Console.WriteLine(val);
}              
    

Open in new window

0
 

Author Closing Comment

by:VBdotnet2005
ID: 39860710
Thank you Fernando
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 39860736
Not a problem, glad to help.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses
Course of the Month13 days, 18 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question