Tayab
Tayab

Reputation: 311

C# Help parsing xml

Good day everyone. I've been trying to get the attributes of a specific XML node but I'm failing. I'm using System.Xml.

Here's the XML code:

<report type="Full" sr="28">
    ...
</report>

I'm trying to get the type and sr attributes.

Here's what I've tried:

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("test.xml");

XmlNodeList reportNodeList = xmlDocument.GetElementsByTagName("report");
XmlAttributeCollection reportNodeAttributeCollection = reportNodeList.Item(0).Attributes;
string reportType = reportNodeAttributeCollection.GetNamedItem("type").ToString(); //Object reference not set to an instance of an object.
string sr = reportNodeAttributeCollection.GetNamedItem("sr").ToString();

I didn't expect it to work and it didn't. I have some experience with parsing XML but only the very basics of it. Could someone help?

Thanks in advance!

Upvotes: 0

Views: 55

Answers (1)

bkdev
bkdev

Reputation: 432

you just need to use Value instead of ToString:

string reportType = reportNodeAttributeCollection.GetNamedItem("type").Value;
string sr = reportNodeAttributeCollection.GetNamedItem("sr").Value;

Upvotes: 3

Related Questions