C
C#3y ago
yatta

❔ How to get an attribute from xml file

So I have an xml file like this
5 Replies
yatta
yattaOP3y 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
Anchy3y 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
yattaOP3y ago
ye i just figure out the same myself many thanks
Anchy
Anchy3y ago
oh okay no problem haha
Accord
Accord3y 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.
Want results from more Discord servers?
Add your server