子节点存在问题 [英] An issue with Child Nodes
问题描述
我需要检查给定节点是否有子节点,使用
I need to check if a given node has child nodes or not , this may seem simple to implement using
node.childnode.count或node.haschildnodes,但是如果父节点没有子节点但是具有值,例如
node.childnode.count or node.haschildnodes , however if the parent node does not have child nodes but has a value for example
1< city> New York< / city>
1 <city>New York</city>
2< city>
2 <city>
< zone> Manhattan< / zone>
<zone>Manhattan</zone>
< zone> Staten Island< / zone>
<zone>Staten Island</zone>
< / city>
</city>
此处有1 I需要将节点设置为xpath ... / city为node.childnode.count或node.haschildnodes返回false,但只要此节点的值为'New York'为1,它就会继续返回true。这种例外行为是否有不同的方式让
这个起作用?这使得很难区分1& 2。
here with 1 I need the node set to xpath .../city to return false for node.childnode.count or node.haschildnodes but as long as this node has a value 'New York' for 1 it continues to return true. is this excepted behavior is there a different way to get this to work? this makes it difficult to distinguish between 1 & 2.
只是为了完成查询,这是我用来加载xml的代码。
Just to complete the query this is code I use to load the xml.
xmldoc = New XmlDocument
xmldoc.Load(xmlfilePath)
xmln = xmldoc.SelectSingleNode(xPath)
xmldoc = New XmlDocument
xmldoc.Load(xmlfilePath)
xmln = xmldoc.SelectSingleNode(xPath)
使用SelectSingleNode或selectnode似乎无关紧要,我通过检查xmln.FirstChild.Name<>来解决这个问题。 "#text",在寻找处理任何子依赖关系之前,我觉得这有点天真,如果有更好的方法可以知道
。
does not seem to matter whether you use SelectSingleNode or selectnode , i have worked around this by checking for xmln.FirstChild.Name <> "#text", before looking to process for any child dependency, i find this a bit naif and need to know if there is a better way to get this done.
推荐答案
XmlDocument 是微软.NET框架中的DOM实现,在该模型中如果你有例如
XmlDocument is the DOM implementation in Microsoft's .NET framework, in that model if you have e.g.
< foo> bar< / foo>
<foo>bar</foo>
那么" FOO" XmlElement对象确实有一个子节点,一个值为"bar"的XmlText节点。因此,HasChildNodes确实是真的,只有你有例如
then the "foo" XmlElement object has indeed one child node, an XmlText node with Value "bar". Thus HasChildNodes is indeed true, it is only false if you have e.g
< foo />
<foo/>
或
< foo>< / foo>
<foo></foo>
如果要检查元素节点是否没有元素子节点,那么可以使用例如
If you want to check whether an element node has no element child nodes then you could use e.g.
if(node.SelectSingleNode(" *")== null)
if (node.SelectSingleNode("*") == null)
with C#或
if node.SelectSingleNode( < *")Nothing Then
If node.SelectSingleNode("*") Is Nothing Then
与VB.net。
这篇关于子节点存在问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!