选择子节点,但使用 XPath 忽略非元素? [英] Select child nodes, but ignore non-elements with XPath?

查看:35
本文介绍了选择子节点,但使用 XPath 忽略非元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以以下 XML 文档为例:

Given the following XML document for example:

<?xml version="1.0"?>
<UrdaObject>
  <Date>
    <Year>2011</Year>
    <Month>5</Month>
    <Day>18</Day>
    <Hours>8</Hours>
    <Minutes>47</Minutes>
    <Seconds>36</Seconds>
  </Date>
  <random_value>24</random_value>
</UrdaObject>

了解 child::node() - 选择当前节点的所有子节点 我将如何创建一个 XPath(从根开始)选择所有子节点,除了文本、评论和其他非元素.例如,当使用此代码在 WPF 中创建树视图时:

And the understanding the child::node() - Selects all child nodes of the current node how would I create an XPath (starting from the root) that would select all child nodes EXCEPT text, comments, and other things that are NOT elements. For example, when using this code to create a tree view in WPF:

// x is some XmlDocument, xmlTree is my WPF TreeView
XmlDataProvider provider = new XmlDataProvider();
provider.Document = x;
Binding binding = new Binding();
binding.Source = provider;
binding.XPath = "child::node()";
xmlTree.SetBinding(TreeView.ItemsSourceProperty, binding);

我将如何创建我的 XPath 语句,以便我构建一个树视图,其中节点一直向下并在原始文本之前停止?例如,它会生成一个视图:

How would I go about creating my XPath statement so I build a treeview with nodes going all the way down and stopping before the raw text? For example it would generate a view of:

UrdaObject
  Date
    Year
...

代替...

UrdaObject
  Date
    Year
      2011 (Don't want this!)
...

示例 XML 文件仅用于解释我的情况.该表达式应该能够导航任何有效的 XML 文件并提取元素,但不能提取单个文本.

The sample XML files is just for me to explain my situation. The expression should be able to navigate any valid XML file and pull the elements, but not the individual text.

我们是如何解决这个问题的?我已将 child::node() 的所有引用切换到 child::*.但是,我没有更正我的 XAML 中的一行,即拉取 child::node().更正这一行使应用程序正确运行......让我觉得很傻.

How did we fix this? I had switched all references of child::node() to child::*. However, I had NOT corrected one line in my XAML, which was pulling child::node(). Correcting this line made the application behave correctly... and made me feel silly.

推荐答案

child::node() 查找所有子节点.child::* 查找所有 element 节点.

child::node() finds all child nodes. child::* finds all element nodes.

这篇关于选择子节点,但使用 XPath 忽略非元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆