【问题标题】:How to get the just the Content inside an XElement如何获取 XElement 中的内容
【发布时间】:2012-05-15 02:03:23
【问题描述】:

如何使用 linq2sql 获取包含任何匹配内容(不包括任何嵌套元素)的节点。

换句话说,我有一个 XElement 包含

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

我想得到第一个

元素,因为它的内容在 Trimmed 时正是“内容”

【问题讨论】:

    标签: .net xml linq xml-parsing linq-to-xml


    【解决方案1】:

    对于非常大的 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;
                }
            }
        }
    }
    

    【讨论】:

    • 是的,我有一个类似的hackaround(我首先过滤掉任何元素的那些),但我想知道这样做的正确方法是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    相关资源
    最近更新 更多