Linq to XML - element search

I am sure this is basic and probably has been asked before, but I'm just starting to use Linq for XML.

I have simple XML that I need to read and write.

<Documents> ... <Document> <GUID>09a1f55f-c248-44cd-9460-c0aab7c017c9-0</GUID> <ArchiveTime>2012-05-15T14:27:58.5270023+02:00</ArchiveTime> <ArchiveTimeUtc>2012-05-15T12:27:58.5270023Z</ArchiveTimeUtc> <IndexDatas> <IndexData> <Name>Name1</Name> <Value>Some value</Value> <DataType>1</DataType> <CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime> <CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc> </IndexData> <IndexData> <Name>Name2</Name> <Value>Some value</Value> <DataType>3</DataType> <CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime> <CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc> </IndexData> ... </IndexDatas> </Document> ... </Documents> 

I have a “Documents” node that contains a bunch of “Document” nodes.

I have a document GUID and the name is "IndexData". I need to find the document by GUID and check if it has an "IndexData" with some name. If he does not have it, I need to add it.

Any help would be appreciated since I am having trouble reading and finding proxy elements.

I'm currently trying to use (in C #):

 IEnumerable<XElement> xmlDocuments = from c in XElement .Load(filePath) .Elements("Documents") select c; // fetch document XElement documentElementToEdit = (from c in xmlDocuments where (string)c.Element("GUID").Value == GUID select c).Single(); 

EDIT

 xmlDocuments.Element("Documents").Elements("Document") 

This does not return a result, even tho xmlDocuments.Element ("Documents"). It looks like I can't get Document nodes from node documents.

+6
source share
2 answers

You can find these documents (documents without a corresponding name in the index data) using the code below, after which you can add your elements to the end of the IndexData elements.

 var relatedDocs = doc.Elements("Document") .Where(x=>x.Element("GUID").Value == givenValue) .Where(x=>!x.Element("IndexDatas") .Elements("IndexData") .Any(x=>x.Element("Name") == someValue); 
+7
source

This should work:

 var x = XDocument.Load(filePath); // guid in your sample xml is not a valid guid, so I changed it to a random valid one var requiredGuid = new Guid("E61D174C-9048-438D-A532-17311F57ED9B"); var requiredName = "Name1"; var doc = x.Root .Elements("Document") .Where(d => (Guid)d.Element("GUID") == requiredGuid) .FirstOrDefault(); if(doc != null) { var data = doc.Element("IndexDatas") .Elements("IndexData") .Where(d => (string)d.Element("Name") == requiredName) .FirstOrDefault(); if(data != null) { // index data found } else { // index data not found } } else { // document not found } 
0
source

Source: https://habr.com/ru/post/919822/


All Articles