简体   繁体   中英

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

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();
    }
}

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.

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;
}
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM