I have to parse one xml file to another, strictly defined one. The original file looks something like this:
<Data>
<Client>
<id>ID1</id>
<Details>
<detail1>1</detail1>
<detail2>2</detail2>
</Details>
<Details>
<detail1>3</detail1>
<detail2>4</detail2>
</Details>
</Client>
<Client>
<id>ID2</id>
<Details>
<detail1>1</detail1>
<detail2>2</detail2>
</Details>
</Client>
<Client>
<id>ID3</id>
<Details>
<detail1>1</detail1>
<detail2>2</detail2>
</Details>
</Client>
</Data>
Basically all I need to do is to rewrite the file with different node names and parse some data within nodes, the structure itself remains the same.
Right now I have:
var ClientNodes = xml.SelectNodes("//Client");
for (int i = 0; i < ClientNodes.Count; i++)
{
// this iterates through all Client nodes
var DetailsNodes = xml.SelectNodes("//Details");
for (int j = 0; j < DetailsNodes.Count; j++)
{
// this iterates through ALL "//Details" nodes and that's the problem
}
}
If I just loop through the Details node as seen above, I would recieve something like:
<Client>
<id>ID1</id>
<Details>
<detail1>1</detail1>
<detail2>2</detail2>
</Details>
<Details>
<detail1>3</detail1>
<detail2>4</detail2>
</Details>
<Details>
<detail1>1</detail1>
<detail2>2</detail2>
</Details>
<Details>
<detail1>1</detail1>
<detail2>2</detail2>
</Details>
I have no clue how to approach this problem. The main issue is that some Client nodes can have 2 or more Details nodes.
The best solution (I think) would be finding a way to iterate through all nodes within a single Client node, but I have not idea if that's possible (and that's why I decided to write my problem here), plus the files I have to deal with have ~20 nodes within a single Details node.
I would strongly recommend using LINQ to XML instead of XPath for this. (You can use XPath, certainly - but it's less readable IMO. You'd just need to use ClientNodes[i].SelectNodes("Details")
.)
var xml = XDocument.Load(...);
foreach (var client in xml.Root.Elements("Client"))
{
// Do whatever you need to here
foreach (var detail in client.Elements("Details"))
{
// Do whatever you need to here
}
}
LINQ to XML is a wonderful XML API, and well worth learning about...
See more on this question at Stackoverflow