Click here to Skip to main content
14,921,361 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
suppose i have a samplexml like below,
<myData>
      <data key="abc" value="11 " />
      <data key="def" value="458" />
      <data key="ghi" value="89" />
      <data key="jkl" value="5" />
      <data key="mno" value="563" />
      <data key="pqr" value="200" />
    </myData>

how can i get each value in different strings
like:
str1=11;
str2=458;
.
.
.
likewise.

how can i fetch the value by its key using
XmlNode


What I have tried:

 var root = new XmlDocument();
root.Load(@"samplexml.xml");
XmlNode nodeObj = root.SelectSingleNode("/myData/add[@key=abc]");
string str1= nodeObj.Attributes["value"].Value;
Posted
Updated 6-Nov-20 7:54am
v3
Comments
raddevus 6-Nov-20 13:47pm
   
Also, the value is an _attribute_ of the XML tag. I'm assuming you're attempting to get the value of the attribute which is named value.
The value of a tag would be something like <title>The Bering Sea: A Book About Sea Life </title> It's what is between the tags. An attribute value is different.
PIEBALDconsult 6-Nov-20 15:07pm
   
Try : "/myData/data[@key='abc']"

1 solution

Is it this : XmlDocument.GetElementsByTagName Method (System.Xml) | Microsoft Docs[^]
C#
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.Load("books.xml");

    //Display all the book titles.
    XmlNodeList elemList = doc.GetElementsByTagName("data");
    for (int i=0; i < elemList.Count; i++)
    {
      Console.WriteLine(elemList[i].InnerXml);
    }
  }
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900