简体   繁体   中英

linq to xml, read xml file

I am struggling to read this xml file in linq to xml. Can someone help me here. I need to read each track information.

<playlist version="1" xmlns="http://xspf.org/ns/0/" xmlns:jwplayer="http://developer.longtailvideo.com/trac/wiki/FlashFormats">
<title>Some title here</title>
<creator>Some creater</creator>
<info>somesite.com</info>
    <trackList>
        <track>
            <title>Title 1</title>
            <creator>Creater 1</creator>
            <location>location 1</location>
        </track>
        <track>
            <title>Title 2</title>
            <creator>Creater 2</creator>
            <location>location 2</location>
        </track>
    </trackList>
</playlist>

This is what I am trying to do.

XElement xelement1 = XElement.Load(@"pathtoxmlfile\my.xml");

IEnumerable<XElement> tracks= xelement1.Elements();
// Read the entire XML
foreach (var track in tracks.Descendants("track"))
{
    Console.WriteLine(track );
    Console.ReadLine();
}

I am using C#.

Thanks Parminder

You forget to include namespace name, do the following changes:

    XNamespace defNs = "http://xspf.org/ns/0/";

And

    foreach (var track in tracks.Descendants(defNs + "track"))
XElement tracks = XElement.Load(@"pathtoxmlfile\my.xml");  
foreach (var track in tracks.Descendants("track"))
{
  Console.WriteLine((string)track.Element("title"));
  Console.WriteLine((string)track.Element("creator"));
  Console.WriteLine((string)track.Element("location"));
}
  1. Why do you load your document into XElement instead of XDocument ?

  2. You have to use XNamespace instance within your query because your document uses default namespace xmlns="http://xspf.org/ns/0/" .

     var ns = XNamespace.Get("http://xspf.org/ns/0/"); 
  3. You can use LINQ query to get a collection with your data extracted from XML document. Then you can iterate over that collection and do whatever you need.

     var tracks = (from t in xDoc.Root.Element(ns + "trackList").Elements(ns + "track") select new { Title = (string)t.Element(ns + "title"), Creator = (string)t.Element(ns + "creator"), Location = (string)t.Element(ns + "location") }).ToList(); 

    tracks will be a List<T> where T is anonymous type with 3 string properties: Title , Creator and Location .

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