Reputation: 219
I'm Trying to check XML elements for specific attributes so I can keep from saving duplicate element entries. the XML looks more or less like this:
<root>
<artist name="Coldplay">
<track name="yellow" artist="Coldplay" url="coldplay.com/yellow" playCount="123" />
<track name="fix you" artist="Coldplay" url="coldplay.com/fixyou" playCount="135" >
</artist>
//ect.
</root>
google and various search results suggest something like
[@id='foo']
but i don't know what that is and for reasons that might be more obvious to you than to me i can't "google" a collection of special characters like that without getting bizarre results. So If anyone can offer a suggestion for an if checking statement I'd be much obliged! or a name or link for how special characters are used in C#.
Upvotes: 1
Views: 3175
Reputation: 1500485
That's an XPath expression - but personally, I'd use LINQ to XML for the searching myself:
XDocument doc = XDocument.Load("test.xml");
var track = doc.Descendants("track")
.Where(t => (string) t.Attribute("id") == "foo")
.FirstOrDefault();
(Use Single
, SingleOrDefault
, First
etc if you want to.)
Upvotes: 1
Reputation: 54378
It's an XPath expression. You can use them along with a variety of XML-related objects in c#.
XmlDocument xd = new XmlDocument();
xd.LoadXml( xmlString );
XmlNodeList nodes = xd.SelectNodes( "//root/artist/track[@name='yellow']" );
General Reference: http://msdn.microsoft.com/en-us/library/ms256086.aspx
XPath with LINQ: http://msdn.microsoft.com/en-us/library/bb675183.aspx.
Upvotes: 2