Ask Your Question
0

How can I retrieve the content of an XML element that has the same tag but a different attribute value using c#?

asked 2022-01-21 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-04-13 18:00:00 +0000

djk gravatar image

You can use LINQ to XML in C# to retrieve the content of an XML element that has the same tag but a different attribute value. Here's an example code snippet:

XDocument doc = XDocument.Load("example.xml");
string attributeValue = "foo";
string elementValue;

XElement element = doc.Descendants("TagName")
                     .Where(e => e.Attribute("AttributeName").Value == attributeValue)
                     .FirstOrDefault();

if (element != null)
{
    elementValue = element.Value;
}

This code loads an XML file into an XDocument object, specifies the attribute value you want to search for, and then retrieves the first element that has the tag name you're looking for and the specified attribute value. Once you have the element, you can access its value by using the Value property. If the element is null, then you know that no element with the specified tag name and attribute value exists in the document.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-21 11:00:00 +0000

Seen: 13 times

Last updated: Apr 13 '21