簡體   English   中英

嘗試記錄從xml根到指定節點的路徑

[英]Trying to record a path from xml root, to a specified node

我希望能夠獲取從xml文檔的根節點到樹中指定節點的路徑。 我現在有一個基本算法,但是它不會刪除不導致指定節點的節點(我想找到從根到該節點的最短路徑)。

private static List<string> firstPath = new List<string>();
private static XmlDocument doc = new XmlDocument();
private static bool run = true;

static void Main(string[] args)
{
    doc.Load("XML doc name");
    foreach(XmlNode node in doc.ChildNodes)
    {
        path("Specified node you want the path to", node);
    }
    printPath(firstPath);
}

private static void path(string name, XmlNode node)
{
    foreach(XmlNode childNode in node.ChildNodes)
    {
        if(childNode.Name == name)
        {
            firstPath.Add(childNode.Name);
            run = false;
        }
        else if(childNode.ChildNodes == null) //last descendant
        {
            firstPath.RemoveAt(firstPath.Count - 1); //remove the most recent
        }
        else
        {
            if (run)
            {
                firstPath.Add(childNode.Name);
                path(name, childNode);
            }
        }
    }
}

private static void printPath(List<string> list)
{
    foreach(string str in list)
    {
        System.Diagnostics.Debug.WriteLine(str);
    }
}

XML文檔示例:

<XML_Tree_Name>
<Root Node>
    <Node 1>
        <Node 2/>
        <Node 3/>
    </Node 1>
    <Node 4>
        <Node 5/>
        <Node 6>
            <Node 7/>
        </Node 6>
    </Node 4>
</Root Node>

假設我要獲取從根到節點7的路徑。該路徑將是Root, 4, 6, 7 但是,它不會刪除沒有導致7的節點,因此記錄的路徑是Root, 1, 2, 3, 4, 5, 6, 7

如何從列表中正確刪除未導致所需節點的節點?

您的代碼無法正常工作,因為所有路徑都將節點添加到列表中。 (== null永遠不會為真,它將是一個空列表。)

為了簡化代碼,請從END開始並向后工作。

var list = new List<XElement>();
var s = @"<RootNode><Node1><Node2/><Node3/></Node1><Node4><Node5/><Node6><Node7/></Node6></Node4></RootNode>";
var doc = XDocument.Parse(s);
var finalNode = doc.XPathSelectElement("//Node7");

for(var currentNode = finalNode; currentNode != null; currentNode = currentNode.Parent)
{
    list.Add(currentNode);
}

foreach(var node in list)
{
    Console.WriteLine(node.Name);
}

另外,如果不需要全局變量,則應避免使用它們。 從函數返回列表:

private static List<XElement> GetPath(...) {...}

static void Main()
{
    var pathList = GetPath(...);
    PrintPath(pathList);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM