Solved

read xml file in C#

Posted on 2014-02-13
7
571 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 62

Expert Comment

by:Fernando Soto
Comment Utility
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 12

Expert Comment

by:Jitendra Patil
Comment Utility
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
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:VBdotnet2005
Comment Utility
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 62

Accepted Solution

by:
Fernando Soto earned 500 total points
Comment Utility
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
Comment Utility
Thank you Fernando
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Not a problem, glad to help.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Find value in LINQ result ? 4 17
Paging GridView 7 32
C# DataGridView_RowsAdded event not firing 1 36
XML & .net 5 16
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

744 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now