日期:2014-05-17 浏览次数:20911 次
XDocument doc = XDocument.Load("c:\\1.txt"); var vs = doc.Descendants("doc"); foreach (var v in vs) { foreach (XElement item in v.Nodes()) { MessageBox.Show(item.Value); } }
------解决方案--------------------
void Main() { XDocument xml=XDocument.Load("c:\\test.xml"); var query=from x in xml.Descendants("doc") select new { author=x.Elements("str").Any(s=>s.Attribute("name").Value=="author")?x.Elements("str").FirstOrDefault(z=>z.Attribute("name").Value=="author").Value:"", id=x.Elements("str").Any(s=>s.Attribute("name").Value=="id")?x.Elements("str").FirstOrDefault(z=>z.Attribute("name").Value=="id").Value:"", title=x.Elements("str").Any(s=>s.Attribute("name").Value=="title")?x.Elements("str").FirstOrDefault(z=>z.Attribute("name").Value=="title").Value:"", }; foreach(var item in query) Console.WriteLine("author:{0}\tid:{1}\ttitle:{2}",item.author,item.id,item.title); }
------解决方案--------------------
foreach (XElement r in XElement.Load(Server.MapPath("~/XMLFile1.xml")).Elements("doc")) { var idobj=r.Elements("str").Where(c => c.Attribute("name").Value=="id"); var titleobj=r.Elements("arr").Where(c => c.Attribute("name").Value == "title"); var authorobj = r.Elements("str").Where(c => c.Attribute("name").Value == "author"); string id="", author="", title = ""; if (idobj.ToList().Count!= 0) id = idobj.First().Value; if (titleobj.ToList().Count != 0) title = titleobj.First().Value; if (authorobj.ToList().Count != 0) author = authorobj.First().Value; Response.Write("id:" + id + "titile:" + title + "author:" + author + "<br>"); }