Vladmere Vladmere - 2 months ago 8
C# Question

Cannot get single XElement from XML

I have an XML file that is structured like this:

<scan client="Computer1" end="9/20/2016 7:00:00 AM" start="9/20/2016 7:00:00 AM">
<childfile>
<name>file.ext</name>
<lastmodified>8/31/2016</lastmodified>
<age>19</age>
</childfile>
<childfile>
<name>file2.ext</name>
<lastmodified>9/1/2016</lastmodified>
<age>18</age>
</childfile>
<childfile>
<name>file3.ext</name>
<lastmodified>8/19/2016</lastmodified>
<age>31</age>
</childfile>
<childfile>
<name>file4.ext</name>
<lastmodified>8/23/2016</lastmodified>
<age>27</age>
</childfile>
</scan>
<scan client="Computer2" end="9/20/2016 7:00:00 AM" start="9/20/2016 7:00:00 AM">
<childfile>
<name>file.ext</name>
<lastmodified>8/31/2016</lastmodified>
<age>19</age>
</childfile>
<childfile>
<name>file2.ext</name>
<lastmodified>9/1/2016</lastmodified>
<age>18</age>
</childfile>
<childfile>
<name>file3.ext</name>
<lastmodified>8/19/2016</lastmodified>
<age>31</age>
</childfile>
<childfile>
<name>file4.ext</name>
<lastmodified>8/23/2016</lastmodified>
<age>27</age>
</childfile>
</scan>


I am sending a new XML element that would look like those above, it will be something like:

<scan client="Computer1" end="9/25/2016 7:00:00 AM" start="9/25/2016 7:00:00 AM">
<childfile>
<name>file.ext</name>
<lastmodified>8/31/2016</lastmodified>
<age>19</age>
</childfile>
<childfile>
<name>file2.ext</name>
<lastmodified>9/1/2016</lastmodified>
<age>18</age>
</childfile>
</scan>


How do I search the original XML to see if it has a scan section that has a client attribute that matches the one that is provided, and if it does match one, replace that element with the one provided. If it doesn't find a match it will need to just add that element to the existing ones.

I attempted to use:

originalXML.Elements("scan").SingleOrDefault(e => e.Attribute("client").Value == client)


where the client var is set using

string client = replacementXML.Attribute("client").Value;


it seems like this is returning null every time even though i checked the client string and it is set to "Computer1".

Any thoughts on why this is always returning null?

Answer

You have two issues...

  1. Malformed XML - You must have a root element
  2. You need to reference your "scan" elements off your root object

So your linq2xml will look like this...

var client = replacementXML.Root.Attribute("client").Value;
var match = originalXML.Root.Elements("scan")
       .SingleOrDefault(e => e.Attribute("client").Value == client);

OK well I guess I'm a little late.. I see your comment that you got it fixed. :)