?
Solved

read xml file in C#

Posted on 2014-02-13
7
Medium Priority
?
586 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 63

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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 63

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 63

Expert Comment

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

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses

762 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