matrix
matrix

Reputation: 3090

How to find a XML tag with a specific attribute (in C#)

I need to get a list of tags that contain a specific attribute. I am using DITA xml and I need to find out all tags that has a href attribute.

The problem here is that the attribute may be inside any tag so XPath will not work in this case. For example, an image tag may contain a href, a topicref tag may contain a href, and so on.

So I need to get a XmlNodeList (as returned by the getElementByTagName method). Ideally I need a method getElementByAttributeName that should return XmlNodeList.

Upvotes: 1

Views: 993

Answers (2)

user151323
user151323

Reputation:

If you're on C#, then the following approach might work for you:

XDocument document = XDocument.Load(xmlReader);
XAttribute xa = new XAttribute("href", "pic1.jpg");
var attrList = document.Descendants().Where (d => d.Attributes().Contains(xa));

Upvotes: 3

Chris Taylor
Chris Taylor

Reputation: 53719

I might have misunderstood your problem here, but I think you could possibly use an XPath expression.

var nodes = doc.SelectNodes("//*[@href='pic1.jpg']");

The above should return all elements with href='pic1.jpg', where doc is the XmlDocument

Upvotes: 5

Related Questions