日期:2014-05-18  浏览次数:20913 次

linq to xml 的复杂查询
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ZTest_01.XmlTest
{
    class LinqXml
    {
        private const string xmldoc =
@"<?xml version='1.0'?> 
<names xmlns='http://www.piedey.co.jp/example/linqtoxml201003'> 
<table name ='atable'>
  <column id='M0001' Visible='false' name ='一郎'></column> 
  <column id='M0002' Visible='true' name ='次郎'></column> 
  <column id='F0001' Visible='false' name ='花子'></column>
  <column id='F0001' Visible='true' name ='花子2'></column>
</table>
<table name='btable'>
   
  <column id='M0001' Visible='false' name ='AAA'></column> 
  <column id='M0002' Visible='true' name ='BBB'></column> 
  <column id='F0001' Visible='false' name ='CCC'></column>
  <column id='F0001' Visible='true' name ='DDD'></column>
</table>
</names>

";
        static void Main(string[] args)
        {
            var doc = XElement.Parse(xmldoc);
            XNamespace ex = "http://www.piedey.co.jp/example/linqtoxml201003";
            var query = from n in doc.Descendants(ex + "table")
                        where n.Attribute("name").Value == "btable" && n.Element("column").Attribute("Visible").Value.Equals("true")
                        select new
                        {
                            id = n.Element("column").Attribute("id").Value,
                            name = n.Element("column").Attribute("name").Value,
                        };

            foreach (var elem in query)
            {
                Console.WriteLine(elem.id + " " + elem.name);
            }
            Console.Read();
        }

    }
}




查询 table=btable and colmun行的Visible属性是true的 colmun行。
谢谢


------解决方案--------------------
C# code
           XNamespace ex = "http://www.piedey.co.jp/example/linqtoxml201003";
            var query = from x in XDocument.Parse(xmldoc).Descendants(ex + "column")
                        where x.Attribute("Visible").Value == "true" && x.Parent.Attribute("name").Value == "btable"
                        select new { id = x.Attribute("id").Value, name = x.Attribute("name").Value };
            foreach (var q in query)
                Console.WriteLine(q.id + " " + q.name);

------解决方案--------------------
C# code
var stream = new MemoryStream(Encoding.UTF8.GetBytes(xmldoc));
var doc = XDocument.Load(stream);
var ret = doc.Descendants()
    .Where(d => d.FirstAttribute.Value.Equals("btable"))
    .Elements()
    .Where(e => e.Attribute("Visible").Value.Equals("true"))
    .Select(s => new { id = s.Attribute("id"), name = s.Attribute("name") });

foreach (var node in ret)
{
    Console.WriteLine("{0} | {1}", node.id, node.name);
}