我需要一个函数来返回 C# 中所有元素的前序和后序,它返回所有元素的 (XElement, Preorder, Postorder) 列表。我怎样才能做到这一点?
例如,使用此 XML:
<?xml version='1.0' encoding='ISO-8859-1' ?>
<!--
XML-Page generated by PENELOPE.
Copyright (c) 1999 Araneus Group and University 'Roma Tre', Rome, ITALY
All rights reserved.
-->
<SigmodRecord>
<issue>
<volume>11</volume>
<number>1</number>
<articles>
<article>
<title>Architecture of Future Data Base Systems</title>
<authors>
<author position="00">Lawrence A. Rowe</author>
<author position="01">Michael Stonebraker</author>
</authors>
<initPage>30</initPage>
<endPage>44</endPage>
</article>
<article>
<title>Multisafe - A Data Security Architecture</title>
<authors>
<author position="00">Robert P. Trueblood</author>
<author position="01">ii. Rex Hartson</author>
</authors>
<initPage>45</initPage>
<endPage>63</endPage>
</article>
</articles>
</issue>
<issue>
<volume>12</volume>
<number>2</number>
<articles>
<article>
<title>Comparison and Mapping of the Relational and CODASYL Data Models</title>
<authors>
<author position="00">Gary H. Sockut</author>
</authors>
<initPage>55</initPage>
<endPage>68</endPage>
</article>
</articles>
</issue>
</SigmodRecord>
我需要这个答案:
Element = <SigmodRecord>,preorder = 1, postorder = 29
Element = <SigmodRecord/issue>,preorder = 2, postorder = 18
.
.
.
我已经编写了这个类,但它在大型 XML 文件中运行缓慢,因为对于每个元素,它都会处理所有节点!
class CTraversal
{
private int preorderID = 0;
private int postorderID = 0;
public int PreOrderTraversal(XElement RootNode, XElement CurrentNode)
{
if (CurrentNode == RootNode)
{
return ++preorderID;
}
if (RootNode.DescendantNodes().Count() > 1)
{
foreach (var child in RootNode.Elements())
{
if (PreOrderTraversal(child, CurrentNode) != -1) return preorderID;
}
}
return -1;
}
public int PostOrderTraversal(XElement RootNode, XElement CurrentNode)
{
if (RootNode.DescendantNodes().Count() > 1)
{
foreach (var child in RootNode.Elements())
{
if (PostOrderTraversal(child, CurrentNode) != -1) return postorderID;
}
}
if (CurrentNode == RootNode)
{
return ++postorderID;
}
++postorderID;
return -1;
}
}