Nurullah.c Nurullah.c - 4 months ago 23
C# Question

Get collection of same element value from xml using linq

This is my xml code

<?xml version="1.0" encoding="utf-8"?>
<Event xmlns="">
<System>
<Provider Name="" />
<EventID>4624</EventID>
<Version>0</Version>
<Level>0</Level>
<Task>12544</Task>
<Opcode>0</Opcode>
<Keywords>0x0000</Keywords>
<TimeCreated SystemTime="20Z" />
<EventRecordID>911588</EventRecordID>
<Correlation />
<Execution ProcessID="608" ThreadID="704" />
<Channel>Security</Channel>
<Computer></Computer>
<Security />
</System>
<EventData>
<Data Name="SubjectUserSid">S-1-0-0</Data>
<Data Name="SubjectUserName">-</Data>
<Data Name="SubjectDomainName">-</Data>
<Data Name="SubjectLogonId">0x0</Data>
<Data Name="TargetUserSid">S1937-12707</Data>
<Data Name="TargetUserName"></Data>

</EventData>
</Event>


I want to get
Name
attribute value and element value of all the
Data
node

I have tried this,

XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load("C:\\Users\\bk.koc\\Desktop\\Gelenxml.xml");

foreach (XmlNodeList node in xmlDoc.GetElementsByTagName("Data"))
{
MessageBox.Show(node.Attributes["Name"].Value);
MessageBox.Show(node["Name"].Value);
}


I am getting all names but this gives me an error.


An unhandled exception of type 'System.NullReferenceException'
occurred in WindowsFormsApplication4.exe

Additional information: Object reference not set to an instance of an
object.


How can fix that

Answer

You can get by this

XDocument doc = XDocument.Load(@"C:\Users\bk.koc\Desktop\Gelenxml.xml");
var a = from m in doc.Descendants("EventData").Elements("Data")
         select new
          {
            Name = m.Attribute("Name").Value,
            Value = m.Value

          };

then

foreach (var v in a)
   {
       MessageBox.Show(v.Name);
       MessageBox.Show(v.Value);

   }

Update I have used this xml

<?xml version="1.0" encoding="utf-8"?>
<EventData>
  <Data Name="SubjectUserSid">S-1-0-0</Data> 
  <Data Name="SubjectUserName">-</Data> 
  <Data Name="SubjectDomainName">-</Data> 
  <Data Name="SubjectLogonId">0x0</Data>
</EventData>