Sarfaraz Ali
Sarfaraz Ali

Reputation: 151

How to Read xml file In C#

this is my xml file

<problem>
<sct:fsn>Myocardial infarction (disorder)</sct:fsn>    
<sct:code>22298006</sct:code>
<sct:description>Heart attack</sct:description>
<sct:description>Infarction of heart</sct:description>
<sct:description>MI - Myocardial infarction</sct:description>
<sct:description>Myocardial infarct</sct:description>
<sct:description>Cardiac infarction</sct:description>
</problem> 

I want to read Description section in c#. how can I do this Please help Me ???

thanks

Upvotes: 0

Views: 312

Answers (3)

Megha
Megha

Reputation: 220

I tried this and it works. This is short and you can read the description easily. Assume test.xml is the file you want to read . val will contain the value of decription. Please note that since you are using colon in your xml element name , it is important that you associate a namespace in your XML file for sct.

XElement  RootNode = System.Xml.Linq.XElement.Load("d:/test.xml");   
foreach (XElement child in RootNode.Elements())
{
    if (child.Name.LocalName.Equals("description"))
    {
        string val = child.Value.ToString();
    }
}

Upvotes: 1

Jayanti Lal
Jayanti Lal

Reputation: 1185

Reading Xml with XmlReader :

   XmlReader xReader = XmlReader.Create(new StringReader(xmlNode));
while (xReader.Read())
{
    switch (xReader.NodeType)
    {
        case XmlNodeType.Element:
            listBox1.Items.Add("<" + xReader.Name + ">");
            break;
        case XmlNodeType.Text:
            listBox1.Items.Add(xReader.Value);
            break;
        case XmlNodeType.EndElement:
            listBox1.Items.Add("");
            break;
    }
}

Reading XML with XmlTextReader :

 XmlTextReader xmlReader = new XmlTextReader("d:\\product.xml");
 while (xmlReader.Read())
    {
switch (xmlReader.NodeType)
{
    case XmlNodeType.Element:
        listBox1.Items.Add("<" + xmlReader.Name + ">");
        break;
    case XmlNodeType.Text:
        listBox1.Items.Add(xmlReader.Value);
        break;
    case XmlNodeType.EndElement:
        listBox1.Items.Add("");
        break;
}
 }

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172618

Try like this:

foreach(XmlNode node in doc.DocumentElement.ChildNodes){
   string text = node.InnerText; 
}

You can read the attribute as

string text = node.Attributes["sct:description"].InnerText;

You can also refer: LINQ to XML

LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. LINQ to XML uses the latest .NET Framework language capabilities and is comparable to an updated, redesigned Document Object Model (DOM) XML programming interface.

Upvotes: 0

Related Questions