I am using the below XML file and trying to get all the distinct files from the XML tree. I want to store the distinct paths in a file.
The duplicate paths are eliminated as shown in the last part of the question.
Please help me get a c# code to do that.
******************************************
# of paths in the XML Tree are 10
/RootElement
/RootElement/FirstChild
/RootElement/SecondChild
/RootElement/SecondChild
/RootElement/FirstChild/Leaf1
/RootElement/FirstChild/Leaf2
/RootElement/SecondChild/Leaf3
/RootElement/SecondChild/Leaf4
/RootElement/SecondChild/Leaf3
/RootElement/SecondChild/Leaf5
******************************************
# of distinct paths in the XML Tree are 9
/RootElement
/RootElement/FirstChild
/RootElement/SecondChild
/RootElement/SecondChild
/RootElement/FirstChild/Leaf1
/RootElement/FirstChild/Leaf2
/RootElement/SecondChild/Leaf3
/RootElement/SecondChild/Leaf4
/RootElement/SecondChild/Leaf5
Thanks,
sana.
sana fatimaPosted Dec 15, 2010, 5:07 PM
What changes should i make to the code,
1) If i want to read the file from a specific location on the computer.(Like D:\programs\data.XML)
2) If i want all the paths(not unique) and store them in a text file to a specific location.
My XML file is huge.
Also i want to ignore the Attribute values with in the tag like "Key="ms/Jhon" in
I am only looking for Elements information in the XML document and want to ignore the rest other things.
Please reply.
Zoran HorvatPosted Dec 15, 2010, 4:38 AM
using System;
using System.Xml;
using System.Collections.Generic;
namespace Test
{
class Program
{
static XmlDocument LoadDocument()
{
string plain =
@"
XmlDocument doc = new XmlDocument();
doc.LoadXml(plain);
return doc;
}
static string[] ExtractUniquePaths(XmlDocument doc)
{
Stack
Stack
Dictionary
elementStack.Push(doc.DocumentElement);
pathStack.Push("/" + doc.DocumentElement.Name);
while (elementStack.Count > 0)
{
XmlElement el = elementStack.Pop();
string path = pathStack.Pop();
if (!uniquePaths.ContainsKey(path))
uniquePaths.Add(path, el);
foreach (XmlNode child in el.ChildNodes)
if (child is XmlElement)
{
XmlElement childElement = child as XmlElement;
string childPath = path + "/" + childElement.Name;
elementStack.Push(childElement);
pathStack.Push(childPath);
}
}
string[] paths = new string[uniquePaths.Count];
uniquePaths.Keys.CopyTo(paths, 0);
Array.Sort(paths);
return paths;
}
static void Main(string[] args)
{
XmlDocument doc = LoadDocument();
string[] paths = ExtractUniquePaths(doc);
Console.WriteLine("{0} unique paths:", paths.Length);
for (int i = 0; i < paths.Length; i++)
Console.WriteLine(paths[i]);
}
}
}
XML document is traversed depth-first and all paths are stored in a dictionary so that no duplicates can occur.