我有一个如下的 xml:
<return>
<exams>
<remove>
</remove>
<add>
<exam errorCode="0" examRef="1" />
</add>
<add>
<exam errorCode="0" examRef="1" />
<exam errorCode="0" examRef="1" />
</add>
</exams>
</return>
我正在构建一个实用程序,可以通过提取其祖先层次结构来区分每个节点。例如:
return[0].exams[0].add[0].exam[0] //This indicates the first exam node in the first add element.
return[0].exams[0].add[1].exam[0] //This indicates the first exam node in the second add element.
return[0].exams[0].add[1].exam[1] //This indicates the second exam node in the second add element.
等等。我到目前为止的代码是:
private string GetAncestorNodeAsString(XElement el)
{
string ancestorData = string.Empty;
el.Ancestors().Reverse().ToList().ForEach(anc =>
{
if (ancestorData == string.Empty)
{
ancestorData = String.Format("{0}[0]", anc.Name.ToString());
}
else
{
ancestorData = String.Format("{0}.{1}[0]", ancestorData, anc.Name.ToString());
}
});
if (ancestorData == string.Empty)
{
ancestorData = el.Name.ToString();
}
else
{
ancestorData = String.Format("{0}.{1}[0]", ancestorData, el.Name.ToString());
}
return ancestorData;
}
此代码返回如下内容:
return[0].exams[0].add[0].exam[0] //zeros here are hardcoded in the code and I need some mechanism to get the position of each of the element in the xml.
我可以建立元素的位置,例如:
var elements = el.Elements().Select((e, index) => new
{
node = e,
position = index
});
但这只会给我一个元素中只有直接子元素的位置。我需要识别所有祖先及其在 xml 中的位置。
有人可以帮忙吗?