user1211185
user1211185

Reputation: 731

How to retrieve attribute from xml

I have the following xml in XmlDocument. I am trying to extract the className from it.

<Registration className="Eng" type="DirectRegistration" state="Activated"     xmlns="http://xyz/Registration">
  <Fields>
    <Field type="abc" value="123456" />
    <Field type="xyz" value="789" />
  </Fields>
</Registration>

I have tried the following code but its not giving me className.

var xmlNode = xmlDoc.DocumentElement;

Can anyone help me to get the value of className out.

Many Thanks

Upvotes: 2

Views: 113

Answers (3)

Mutu Yolbulan
Mutu Yolbulan

Reputation: 1052

you can also use xPath to retrieve the attribute

string className = xmlDocument.SelectSingleNode("//Registration/@className").Value;

Upvotes: 1

Dor Cohen
Dor Cohen

Reputation: 17080

Try using this:

// Trying to parse the given file path to an XML
XmlReader firstXML = XmlReader.Create(XMLPath);
firstXML.ReadToFollowing("Registration");
firstXML.MoveToAttribute("className");
var res = firstXML.Value;

res will hold "className" value.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You were almost there:

var className = xmlDoc.DocumentElement.GetAttribute("className");

xmlDoc.DocumentElement gives you the whole element; GetAttribute pulls an individual named attribute from it.

Upvotes: 4

Related Questions