检查XmlNode是否有孩子 [英] Check if XmlNode has childs
本文介绍了检查XmlNode是否有孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过读取Xml文件来创建TreeNode.我管理了创建ParentNodes(组)的操作,但我想也将用户(Xml子节点)添加到这些组中.
运行此代码后:
I want to make a TreeNode by reading an Xml file. I mananged to create the ParentNodes(The Groups) but I want to add also users(the Xml child nodes) to these groups.
After running this code:
Public Sub ReadGroup_Xml()
GroupsList.Load(xml_path)
Dim TreeNode2, TreeNode3 As TreeNode
Dim names_list1 = GroupsList.GetElementsByTagName("Group_Name")
Dim names_list2 = GroupsList.GetElementsByTagName("User_Initials")
For Each item1 As XmlElement In names_list1
'Here I add the parent nodes
TreeNode2 = New TreeNode(item1.InnerText)
MUsersFrm.TreeView1.Nodes.Add(TreeNode2)
TreeNode2.ImageIndex = 0
'Here I want to add the child nodes
'What is the condition???
For Each item2 As XmlElement In names_list2
TreeNode3 = New TreeNode(item2.InnerText)
TreeNode2.Nodes.Add(TreeNode3)
Next
Next
End Sub
我得到结果:
I get the result:
Group Administrators
- User am
Group Editors
- User am
Group Guests
- User am
正确的结果应该是:
The correct result should be:
Group Administrators
Group Editors
- User am
Group Guests
...因为仅组编辑器"节点包含子节点
我认为注释的文本在创建子节点之前应该有条件.
您可以在这种情况下为我提供帮助吗?
...because only the Group Editors node contains childs nodes
I think that the commented text should have a condition before creating the child nodes.
Can you help me with this condition?
推荐答案
我认为您可以使用
I think you could use
If item1.HasChildNodes Then
过滤出空的父节点.
to filter out the empty parent nodes.
如果您发布了xml文件的示例,将很有帮助,但这是基于此xml的示例.
It would be helpful if you posted a sample of your xml file, but here is an example based on this xml.
<?xml version="1.0" encoding="utf-8" ?>
<groups>
<group Name="Administrators"></group>
<group Name="Editors">
<User_Initials>abc</User_Initials>
<User_Initials>zyz</User_Initials>
</group>
<group Name="Guests"></group>
</groups>
Dim doc As New Xml.XmlDocument
doc.Load("xmlfile1.xml")
Dim groups As Xml.XmlNodeList = doc.SelectNodes("./groups/group")
For Each grp As Xml.XmlElement In groups
Dim node As TreeNode = TreeView1.Nodes.Add(grp.GetAttribute("Name"))
For Each user As Xml.XmlNode In grp.SelectNodes("./User_Initials")
node.Nodes.Add(user.InnerText)
Next
Next
这篇关于检查XmlNode是否有孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文