How do I iterate over all the elements of the XML tree, and access to them? What I mean is that the input gets unknown xml file, and the code itself it iterates not knowing the number of elements and branches.
I know that was a lot of answers on such topics and the solution was ready to implement the code, where the known structures xml.
This is a code which i am using:
class Program
{
static void Process(XElement element)
{
if (!element.HasElements)
{
Console.WriteLine(element.GetAbsoluteXPath());
}
else
{
foreach (XElement child in element.Elements())
{
Process(child);
}
}
}}
static void Main()
{
var doc = XDocument.Load("C:\\Users\\Błażej\\Desktop\\authors1.xml");
List<string> elements = new List<string>();
Program.Process(doc.Root);
Console.ReadKey();
}
public static class XExtensions
{
public static string GetAbsoluteXPath(this XElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
Func<XElement, string> relativeXPath = e =>
{
int index = e.IndexPosition();
string name = e.Name.LocalName;
return (index == -1) ? "/" + name : string.Format
(
"/{0}[{1}]",
name,
index.ToString()
);
};
var ancestors = from e in element.Ancestors()
select relativeXPath(e);
return string.Concat(ancestors.Reverse().ToArray()) +
relativeXPath(element);
}
public static int IndexPosition(this XElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
if (element.Parent == null)
{
return -1;
}
int i = 1;
foreach (var sibling in element.Parent.Elements(element.Name))
{ // czyli patrzymy na rodzeństwo, czy występują podobne np. au_id[1], au_id[2]
if (sibling == element)
{
return i;
}
else
{
i++;
}
}
throw new InvalidOperationException
("element has been removed from its parent.");
}
Now how can i add some elements to exisitng nodes by iterate ? It's possible ?