Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Experts,
Having the following XML file sample:
XML
<App action="A" id="1">
<BaseVeh id="123" /><!-- comment -->
<Qty>1</Qty>
<PartType id="123" /><!-- comment -->
<Part>part name</Part>
</App>

I want to read the whole nodes/comments and save to SQL table.
I managed to read all the nodes, save them no problem, also managed to read all comments and save them in separate table too.
I want to save the comment alongside the corresponding node, in other words, if i'm saving partTypeId i want to save it's comment too in the same table, is it possible to do so?

What I have tried:

Here's how I read the XML and save:
C#
XmlDocument mydoc = new XmlDocument();
mydoc.Load("https://abc/file.xml");
XmlElement element = mydoc.DocumentElement;
XmlNodeList nodes = element.SelectNodes("App");
foreach (XmlNode node in nodes)
{
if (node != null)
{
//save to DB
}
}

This is what I used to save comments separately:
C#
XDocument Doc=XDocument.Load("https://abc/file.xml");
foreach (var node in Doc.Descendants("App").Nodes())
{
if (node is XComment)
{
   //save comments
                    
}
Posted
Updated 24-Feb-16 5:48am
Comments
Richard MacCutchan 24-Feb-16 11:43am    
You need to capture the comment nodes at the same time as the normal ones, so they are caught in sequence.
Samira Radwan 24-Feb-16 11:46am    
thank you, this is what i have done

1 solution

I found out how to do so:
C#
XDocument Doc=XDocument.Load("https://abc/file.xml");
foreach (var node in Doc.Descendants("App").Nodes())
{
if (node is XComment)
{
   //assign comment to variable
  //save both to DB -- saving here because comments are after the data nodes.
                    
}
else if(node is XComment==false)
{
//assign the needed id to variable
}
 
Share this answer
 
v2
Comments
CHill60 24-Feb-16 11:54am    
There is no need for the if(node is XComment==false) the node is either an XComment or it is not.
Also you implied that the comments would come after the data nodes, not before
Samira Radwan 25-Feb-16 8:04am    
for if(node is XComment==false) I totally agree, just use else. for comments coming after data nodes, I actually added to DB in between the first if and it worked, because it will loop first time without comments then second time will do, Hope I explained it correctly, but it really worked :) , excuse my bad English! ;)
CHill60 25-Feb-16 8:28am    
As long as it works. Your English is not too bad - I got what you meant :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900