XMLで、ある一連の要素をXMLNodeListで取得し、その一つが何番目の親の子になるか確かめるには、次のサンプルコードのようにすればわかります。 先にサンプルとなるXMLを示します。
<root>
<parent name="1">
<child>aaa</child>
</parent>
<parent name="2">
<child>bbb</child>
</parent>
<parent name="3">
<child>ccc</child>
</parent>
</root>
次にサンプルコードを示します。
比較でやっていることは、同じインスタンスかどうかを比較しています。
C#
using System.Xml;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
XmlDocument doc = new XmlDocument();
doc.Load("..\\..\\XMLFile1.xml");
//親のリストを取得
XmlNodeList listParent = doc.GetElementsByTagName("parent");
//子供のリストを取得
XmlNodeList listChild=doc.GetElementsByTagName("child");
for (int i = 0; i < listParent.Count - 1; i++)
{
if (listParent[i] == listChild[1].ParentNode)
{
MessageBox.Show((i + 1).ToString() + "番目が同じです。");
}
}
}
}
VB.NET
Imports System.Xml
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim doc As XmlDocument = New XmlDocument()
doc.Load("..\..\XMLFile1.xml")
'親のリストを取得
Dim listParent As XmlNodeList = doc.GetElementsByTagName("parent")
'子供のリストを取得
Dim listChild As XmlNodeList = doc.GetElementsByTagName("child")
For i As Integer = 0 To listParent.Count - 2 Step 1
If listParent(i) Is listChild(1).ParentNode Then
MessageBox.Show((i + 1).ToString() + "番目が同じです。")
End If
Next
End Sub
End Class
