有没有一种方法来使用C#或VB的XML发现最里面的节点递归递归、节点、方法来、里面

2023-09-06 09:10:38 作者:流年、素写一世繁华

我有一个XML文件中说

I have an XML file say

  <items>
      <item1>
        <piece>1300</piece>
        <itemc>665583</itemc> 
      </item1>
      <item2>
        <piece>100</piece>
        <itemc>665584</itemc>
      </item2>
    </items>

我想写一个C#应用程序来获取所有的X-路径内大多数节点,例如:

I am trying to write a c# application to get all the x-path to inner most nodes eg :

items/item1/piece
items/item1/itemc
items/item2/piece
items/item2/itemc

有没有办法使用C#或VB做呢?谢谢你提前为可能的解决方案。

Is there a way to do it using C# or VB?Thank you in advance for a probable solution.

推荐答案

你去那里:

static void Main()
{
   XmlDocument doc = new XmlDocument();
   doc.Load(@"C:\Test.xml");

   foreach (XmlNode node in doc.DocumentElement.ChildNodes)
   {
        ProcesNode(node, doc.DocumentElement.Name);
   }
}


    private void ProcesNode(XmlNode node, string parentPath)
    {
        if (!node.HasChildNodes
            || ((node.ChildNodes.Count == 1) && (node.FirstChild is System.Xml.XmlText)))
        {
            System.Diagnostics.Debug.WriteLine(parentPath + "/" + node.Name);
        }
        else
        {
            foreach (XmlNode child in node.ChildNodes)
            {
                ProcesNode(child, parentPath + "/" + node.Name);
            }
        }
    }

上面code将产生的任何类型的文件的所需的输出。请加检查等。无论需要。 主要的部分是,我们忽略文本节点的输出(文本节点内)。

The above code will generate the desired output for any type of file. Please add checks whereever required. The main part is that we ignore the Text node (Text inside the node) from output.