为 .Net XmlDocument 实现 GetByClassName

发布于 2024-07-07 23:06:49 字数 112 浏览 7 评论 0原文

我正在使用 XmlDocument 来解析和操作 XHTML 字符串,将一些节点转换为非 HTML 节点。

获取具有给定类名的所有节点的列表的最佳方法是什么? 可以用XPath来完成吗?

I am using an XmlDocument to parse and manipulate an XHTML string, converting some nodes to non-HTML nodes.

What is the best way to get a list of all nodes with a given class name? Can it be done with XPath?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娇纵 2024-07-14 23:06:49

与给定的班级? 如果它只是一个类,那么您应该能够执行类似 .SelectNodes("//*[@class='foo']") 的操作。 如果它不是 xhtml,那么 HTML Agility Pack 值得一看。

在客户端,jQuery 将是一个不错的选择 - 并且支持复合类名。

如果单个元素上有多个类名,并且需要在服务器上处理它,我希望您可能需要首先找到候选类(“//*[@class!='']),然后循环它们执行 Split() 并检查结果中的类名;即手动将其分开,

用 LINQ 术语来说,类似于:

        var qry = from XmlElement el in d.SelectNodes("//*[@class!='']")
                  let classes = el.GetAttribute("class").Split(new[] {' '},
                          StringSplitOptions.RemoveEmptyEntries)
                  where classes.Contains("foo")
                  select el;

With a given class? If it is just the one class, then you should be able to do something like .SelectNodes("//*[@class='foo']"). If it isn't xhtml, then the HTML Agility Pack is worth looking at.

At the client, jQuery would be a good option - and supports composite class names.

If you have multiple class names on individual elements, and need to handle it at the server, I expect you might need to find the candidate classes first ("//*[@class!='']), and then loop over them doing a Split() and checking for the class-name in the results; i.e. pull it apart manually.

In LINQ terms, something like:

        var qry = from XmlElement el in d.SelectNodes("//*[@class!='']")
                  let classes = el.GetAttribute("class").Split(new[] {' '},
                          StringSplitOptions.RemoveEmptyEntries)
                  where classes.Contains("foo")
                  select el;
预谋 2024-07-14 23:06:49

是的,使用 XPath 很容易:

//*[@class='foo']

Yes, it's easy with XPath:

//*[@class='foo']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文