linq to xml 的复杂查询

duoshanx 2012-04-20 07:50:55

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行。
谢谢
...全文
217 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
duoshanx 2012-04-22
  • 打赏
  • 举报
回复
非常谢谢。
老毕 2012-04-20
  • 打赏
  • 举报
回复
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);
}
huangwenquan123 2012-04-20
  • 打赏
  • 举报
回复
           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);

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧