Not Able to get Attribute having specific element from XML file, using LINQ

How to get attribute having specific element from XML file?

2

xDOC (datatype - xDocument).{XML File}

IEnum_xAttribute (datatype -System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>).

str_Batch (datatype - String).{str_Batch is the name of the element for which the attribute needed to be fetched}

In Assign
IEnum_xAttribute=
(
From el In xDOC.Elements(“cXMLMessageContent”).Elements(“cXML”).Elements(“ShipNotice”).Elements(“Batch”)
Where CStr(el.Element(“BatchID”))=str_Batch
Select el.Attribute(“ProductionDate”)
)

Then used for each activity, to get value of the attribute using log message.

ERROR : For each: An ActivityContext can only be accessed within the scope of the function it was passed into.
Object name: ‘System.Activities.CodeActivityContext’.

While using str_Batch hardcoded in LINQ query i.e “37364564” it is working without any fail.
But I need to use this workflow for multiple XML File, so workflow need to be dynamic.

Any Help will be Great.

@sahilbaglat
welcome to forum

can you share the XML as text file with us?

1 Like

Hey @sahilbaglat
you can try use:
(From el In xDOC.Descendants("Batch") Where el.Element("BatchID") IsNot Nothing AndAlso el.Element("BatchID").Value.Equals(str_Batch) Select el.Attribute("ProductionDate")).ToList()


image

List<XAttribute>(1) { [ProductionDate="2024-01-23"] }

3 Likes

Have also a look at this starter help:

(From el In  xDOC.Descendants("Batch")
Where el.Element("BatchID").Value.Trim.Equals(str_Batch)
Select el.Attribute("ProductionDate").Value
)
1 Like

for this constraint we can eg use , toList, toArray at the end from the LINQ and loop over the different returned result

(From el In  xDOC.Descendants("Batch")
Where el.Element("BatchID").Value.Trim.Equals(str_Batch)
Select pd =el.Attribute("ProductionDate").Value).ToList

would return a string list

1 Like

Thank You So Much Piotr Kołakowski.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.