Linq to XML - Find an element
You can find those docs (docs without related name in index data) with below code, after that you could add your elements to the end of 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);
no9
Updated on July 06, 2020Comments
-
no9 almost 4 years
I am sure that this is basic and probably was asked before, but I am only starting using Linq to XML.
I have a simple XML that i need to read and write to.
<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 bunch of "Document" nodes.
I have GUID of the document and a "IndexData" name. I need to find the document by GUID and check if it has "IndexData" with some name. If it does not have it i need to add it.
Any help would be apreciated, as i have problem with reading and searching trough elements.
Currently I am 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 returns no result, even tho xmlDocuments.Element("Documents") does. It looks like i cant get Document nodes from Documents node.