日期:2014-05-17  浏览次数:20911 次

请教一个xml读取的问题
xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<result name="response" numFound="4" start="0">
<doc>
<str name="id">testdoc</str>
</doc>
<doc>
<str name="author">hello</str>
<str name="id">123</str>
<arr name="title">
<str>123</str>
</arr>
</doc>
<doc>
<str name="author">world</str>
<str name="id">234</str>
<arr name="title">
<str>234</str>
</arr>
</doc>
<doc>
<str name="author">please</str>
<str name="id">345</str>
<arr name="title">
<str>345</str>
</arr>
</doc>
</result>

请问如何将读取每个doc下面的author、id、title,请用C#,万分感谢!

------解决方案--------------------
C# code

            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);
                }
            }

------解决方案--------------------
C# code

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);
}

------解决方案--------------------
C# code

 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>");

            }