C
C#2y ago
yatta

❔ How to get an attribute from xml file

So I have an xml file like this
5 Replies
yatta
yatta2y ago
,and I wanna get the value of the attribute "Name" in the file. This is what i've tried to do.
var docXml = new XmlDocument();

docXml.Load("path");
var node = docXml.SelectNodes("Process");

var process = docXml.SelectSingleNode("/Process").Attributes["/Name"].Value;

Console.WriteLine(process);
var docXml = new XmlDocument();

docXml.Load("path");
var node = docXml.SelectNodes("Process");

var process = docXml.SelectSingleNode("/Process").Attributes["/Name"].Value;

Console.WriteLine(process);
But I keep received null reference exception. Can someone check at point out where i got the problem ?
Anchy
Anchy2y ago
try this:
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><Root><Process Name=\"sublime_text\"><StartTime>14/11/2022 02:20:56</StartTime><KilledTime>14/11/2022 02:20:56</KilledTime></Process></Root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

var node = xmlDoc.SelectSingleNode("/Root/Process").Attributes["Name"];
Console.WriteLine(node.InnerText);
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><Root><Process Name=\"sublime_text\"><StartTime>14/11/2022 02:20:56</StartTime><KilledTime>14/11/2022 02:20:56</KilledTime></Process></Root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

var node = xmlDoc.SelectSingleNode("/Root/Process").Attributes["Name"];
Console.WriteLine(node.InnerText);
yatta
yatta2y ago
ye i just figure out the same myself many thanks
Anchy
Anchy2y ago
oh okay no problem haha
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.