Search code examples
c#xmlxmlreader

Problem in reading XML


Hello Guys can you help me solving my problem in reading xml. I'm just new in xml. Here's the sample xml.

<Org>
    <Org ID="1">
        <OrgNum>1</OrgNum>
        <OrgName>sample1</OrgName>
    </Org>
    <Org ID="2">
        <OrgNum>2</OrgNum>
        <OrgName>sample2</OrgName>
    </Org>
</Org>

I want to get only the OrgName with an Org ID = 2. Here's my sample code but it's read all the text. Help me plz..Tnx

string xml = Application.StartupPath + "\\OrgName.xml";
XmlDocument xmlDoc = new XmlDocument();
if (System.IO.File.Exists(xml))
{
    XmlTextReader textReader = new XmlTextReader(xml);
    textReader.Read();
    while (textReader.Read())
    {
        XmlNodeType nType = textReader.NodeType;
        if (nType == XmlNodeType.Text)
        {
            MessageBox.Show(textReader.Value);
        }
    }
}

Solution

  • A simple way to do it with linq:

     var doc = XDocument.Load(Application.StartupPath + "\\OrgName.xml");
     var result = doc.Root.Elements("Org").Where(x=>x.Attribute("id").ToString()=="2");