简体   繁体   中英

Searching XML Elements by Attributes (C#)

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#.

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 .

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM