Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

writing xml document c#.net loop overlaying elements rather than appending

Posted on 2010-09-08
5
Medium Priority
?
617 Views
Last Modified: 2012-05-10
I'm trying to create an xml document and am having a problem with my loop to create my sub nodes called 'file'.  I am trying to make an xml doc much like the one below.  I have a set of file names that I loop through and get some additional data on and then create an xml set called <file> within the main <package> set.  Subsequently, if I have 10 files, I should have 10 <file> entries.  See below.  It's looping through however rather than create a new entry, it is overlaying the first one.  so when I get all done, I have the last file only.  Below is my code.  I acquired this code from the net somewhere and modified it so I haven't completely come to understand it all just yet and it may need some further modifications as I work it through but for the most part, my xml doc is looking pretty good except for the reuse of rather than adding  of a new <file> set.  The second loop in the code is where I am writing the file elements. Please advise.  Thank you!


<package><origination_id>1</origination_id>
<package_key>00220091231</package_key>
<email_flag>1</email_flag>
<file>
<grouping_level>002</grouping_level>
<statement_dt>2009-12-31</statement_dt>
<file_type>STMT</file_type>
<file_name>CP002STMT20091231.pdf</file_name>
<file_size>94015</file_size>
</file><file>
<grouping_level>002</grouping_level>
<statement_dt>2009-12-31</statement_dt>
<file_type>INV</file_type>
<file_name>CP002INV20091231.pdf</file_name>
<file_size>82015</file_size>
</file></package>

------------------------------------------------
foreach (DataRow dr in InvoicePkgsdt.Rows)
{
      filename = prestageDirectory + "\\CP" + dr["credit_account_nmbr"].ToString().TrimEnd() + Convert.ToDateTime(dr["invoice_dt"]).ToString("yyyyMMdd") + ".DDF";

      XmlDocument xmlDoc = new XmlDocument();
                              
try
      {
            xmlDoc.Load(filename);
      }

      catch (System.IO.FileNotFoundException)
      {
      //if file is not found, create a new xml file
      XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
      xmlWriter.Formatting = Formatting.Indented;
                                                xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                                          xmlWriter.WriteStartElement("Root");
      
      xmlWriter.Close();
      xmlDoc.Load(filename);
      }

XmlNode root = xmlDoc.DocumentElement;
XmlElement PackageElem = xmlDoc.CreateElement("package");
XmlElement OrigIdElem = xmlDoc.CreateElement("origination_id");
XmlElement PackageKeyElem = xmlDoc.CreateElement("package_key");
XmlElement EmailElem = xmlDoc.CreateElement("email_flag");
XmlElement FileElem = xmlDoc.CreateElement("file");
XmlElement GroupingLvlElem = xmlDoc.CreateElement("grouping_level");
XmlElement StatementDateElem = xmlDoc.CreateElement("statement_dt");
XmlElement FileTypeElem = xmlDoc.CreateElement("file_type");
XmlElement FileNameElem = xmlDoc.CreateElement("file_name");
XmlElement FileSizeElem = xmlDoc.CreateElement("file_size");


XmlText OrigIdText = xmlDoc.CreateTextNode("1");
XmlText PackageKeyText = xmlDoc.CreateTextNode(dr["credit_account_nmbr"].ToString().TrimEnd() + Convert.ToDateTime(dr["invoice_dt"]).ToString("yyyyMMdd"));
XmlText EmailText = xmlDoc.CreateTextNode("0");


root.AppendChild(PackageElem);

PackageElem.AppendChild(OrigIdElem);
OrigIdElem.AppendChild(OrigIdText);

PackageElem.AppendChild(PackageKeyElem);

PackageKeyElem.AppendChild(PackageKeyText);

PackageElem.AppendChild(EmailElem);
EmailElem.AppendChild(EmailText);

DataView Reportsdv = new DataView(Reportsdt);
                                    Reportsdv.RowFilter = "credit_account_nmbr = '" + dr["credit_account_nmbr"].ToString()
                                          + "' and invoice_dt = '" + Convert.ToDateTime(dr["invoice_dt"]).ToString() + "'";

Reportsdv.Sort = "report_cd DESC";

XmlText GroupingLvlText = xmlDoc.CreateTextNode(dr["credit_account_nmbr"].ToString().TrimEnd());
XmlText StatementDateText = xmlDoc.CreateTextNode(Convert.ToDateTime(dr["invoice_dt"]).ToString("MM/dd/yyyy"));
XmlText FileTypeText = xmlDoc.CreateTextNode("");
XmlText FileNameText = xmlDoc.CreateTextNode("");
XmlText FileSizeText = xmlDoc.CreateTextNode("");

string archiveDir = ArchiveDirectory + Convert.ToDateTime(dr["invoice_dt"]).ToString("MMyyyy") + "\\";
                                                                        
for (int int_row = 0; int_row < Reportsdv.Count; int_row++)
{
      PackageElem.AppendChild(FileElem);

                                          FileElem.AppendChild(GroupingLvlElem);
                                          GroupingLvlElem.AppendChild(GroupingLvlText);

                                          FileElem.AppendChild(StatementDateElem);
                                          StatementDateElem.AppendChild(StatementDateText);

      FileElem.AppendChild(FileTypeElem);
      FileTypeText.Value = Reportsdv[int_row]["report_file_node"].ToString().TrimEnd();
                                          FileTypeElem.AppendChild(FileTypeText);

      FileElem.AppendChild(FileNameElem);
      FileNameText.Value = Reportsdv[int_row]["FileName"].ToString();
                                          FileNameElem.AppendChild(FileNameText);

      FileElem.AppendChild(FileSizeElem);
      FileInfo fi = new FileInfo(archiveDir + Reportsdv[int_row]["FileName"].ToString());
      FileSizeText.Value = fi.Length.ToString();
                                          FileSizeElem.AppendChild(FileSizeText);

                                          
      File.Copy(archiveDir + Reportsdv[int_row]["FileName"], prestageDirectory + "\\" + Reportsdv[int_row]["FileName"]);

                                          

}

xmlDoc.Save(filename);
}
0
Comment
Question by:mprimmer
  • 3
  • 2
5 Comments
 
LVL 27

Accepted Solution

by:
Shaun Kline earned 2000 total points
ID: 33631283
Move the CreateTextNode calls for the file fields inside your for loop.
You need to create a new node each time through the loop, otherwise, you are just assigning values to the same node.
0
 
LVL 27

Assisted Solution

by:Shaun Kline
Shaun Kline earned 2000 total points
ID: 33631310
Actually, you will probably have to move the CreateElement calls inside that for loop as well.
0
 

Author Comment

by:mprimmer
ID: 33631556
I think that's right but I'm not sure how to dynamically alter the object name for the create element statement.  I want to concatenate the int_row loop variable onto the word "FileElem".  so I can reference FileElem1, fileelem2, ectc.... can't seem to get the syntax right to get it going.  Can you help me?

XmlElement FileElem = xmlDoc.CreateElement("file")

0
 
LVL 27

Expert Comment

by:Shaun Kline
ID: 33636733
If you want to include the loop variable as part of the tagname in your CreateElement call, try this:

XmlElement FileElem = xmlDoc.CreateElement("file" + int_row.ToString())
0
 

Author Comment

by:mprimmer
ID: 33667202
Thank you... that last question wasn't quite what I meant but it was a stupid move on my part anyway.
   Things are working great now.... thanks for your help!!
0

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question