简体   繁体   中英

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!

you just need to use Value instead of ToString :

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

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