2012-05-06 65 views
1

如何使用linq2sql獲取包含任何嵌套元素的任何匹配內容的節點。如何獲取XElement中的內容

換句話說,我有一個包含

<div> 
    <div> 
    <p> 
     The Content 
    </p> 
    <p> 
     Some other content 
    </p> 
    </div> 
</div> 

我想基於這樣的事實,修剪時,其內容正是「內容」

回答

0

這來獲取第一< p>元素的的XElement對於非常大的XML文件可能會很慢,所以有用性取決於您的任務。

namespace ConsoleApplication9 
{ 
    using System.Xml.Linq; 
    using System.Linq; 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      XElement xx = XElement.Parse(@"<div> 
    <div> 
    <p> 
     The Content 
    </p> 
    <p> 
     Some other content 
    </p> 
    </div> 
</div>"); 
      XNode node = xx 
       .DescendantNodesAndSelf() 
       .FirstOrDefault(x => x.ToString().Trim() == "The Content"); 

      if (node != null) 
      { 
       XElement el = node.Parent; 
      } 
     } 
    } 
} 
+0

是的,我得到了一個類似的hackaround去(我第一次過濾出與任何元素的),但我不知道什麼是正確的做法。 –