Linq To Xml实现类似XPath查询(Silverlight下的XPath)

要实现的类似这样的XPath查询
//o1[@id=1]/o2[@id=2]/o3

找不到合适的方法,下面是我使用的笨方法。
说明一下:Silverlight不支持XPath查询。

XML文档如图:

大气象
StringBuilder sb = new StringBuilder();
sb.Append(
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
sb.Append(
"<root><o1 id=\"1\"><o2 id=\"1\"><o3>1</o3><o3>2</o3></o2>");
sb.Append(
"<o2 id=\"2\"><o3>3</o3><o3>4</o3></o2></o1>");
sb.Append(
"<o1 id=\"2\"><o2 id=\"1\"><o3>5</o3><o3>6</o3></o2>");
sb.Append(
"<o2 id=\"2\"><o3>7</o3><o3>8</o3></o2></o1></root>");
XDocument xDoc 
= XDocument.Parse(sb.ToString());

IEnumerable
<XElement> elO3s = null;
IEnumerable
<XElement> elO1s =
from el 
in xDoc.Root.Elements("o1") select el;
foreach (XElement elO1 in elO1s)
{
    
if (elO1.Attribute("id").Value == "1")
    {
        IEnumerable
<XElement> elO2s = elO1.Elements("o2");
        
foreach (XElement elO2 in elO2s)
        {
            
if (elO2.Attribute("id").Value == "2")
            {
                elO3s 
= elO2.Elements("o3");
            }
        }
    }
}
if (elO3s != null)
{
    
foreach (XElement elO3 in elO3s)
    {
        Response.Write(elO3.Value 
+ "<br/>");
    }
}

 

记得
using System.Xml;
using System.Xml.Linq;
using System.Text;

posted @ 2010-07-20 14:17  大气象  阅读(707)  评论(2编辑  收藏  举报
http://www.tianqiweiqi.com