Insert XML string into XML File: Part 2

Thanks to some good help from a previous post, I have been able to create 
well formed xml as part of a report logger app. However, I still have a 
small problem. When I add new xml to the log file, the new nodes are 
appended to the original file. What I really want is for the log file to 
grow as "report nodes" are added. Also, I am a bit concerned about 
performance, particularly as the file grows in size. I must write to an xml 
file (vs. a database) and am trying to understand the best way to do this. I 
prefer to not use "temp files" and would like to just modify the log file 
structure "in-place". Any advice is appreciated. Also, can anyone recommend 
a good book that covers XML issues when programming with Managed VC++? The 
reports I am generating will eventually be analyzed using Excel or some 
other tools such as Crystal Reports.

The follow is a test app that illustrates the problem.

// This is the main project file for VC++ application project
// generated using an Application Wizard.
#include "stdafx.h"
#using <mscorlib.dll>
#using <System.dll>
#using <System.Xml.dll>
//
using namespace std;
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Xml;
int _tmain()
{
FileStream* fs;
XmlDocument* xmlReport;
// Test XML Snippet - emulates a test outcome
String* xmlStr = S"<TestResult><Name>Application Load 
Test</Name><StartTime>21/05/2006 
14:45:58:155</StartTime><StopTime>21/05/2006 
14:46:35:530</StopTime><TestResult>FAIL</TestResult><TestAtoms><TestAtom><Name>RateTest 
1</Name><StartTime>21/05/2006 14:46:20:530</StartTime><StopTime>21/05/2006 
14:46:35:530</StopTime><TestResult>FAIL</TestResult><Duration>15</Duration><Direction>0</Direction><MinRate>255</MinRate><MaxRate>255</MaxRate></TestAtom></TestAtoms></TestResult>";
// the log file
String* sTestLogFile = S"D:\\Development\\LogTest\\ResultLog.xml";
//
try {
  if(File::Exists(sTestLogFile) == true) {
  // file already exist
  fs = File::Open(sTestLogFile, FileMode::Open, FileAccess::ReadWrite, 
FileShare::None);
  xmlReport = new XmlDocument;
  // Open from Stream
  xmlReport->Load(fs);
  XmlDocumentFragment* docFrag = xmlReport->CreateDocumentFragment();
  docFrag->InnerXml = xmlStr;
  XmlNode* ResultsNode = 
xmlReport->DocumentElement->SelectSingleNode("TestResults");
  // ResultsNode->AppendChild(docFrag);
  ResultsNode->PrependChild(docFrag);
  //xmlReport->DocumentElement->PrependChild(parentNode);
} else {
  // no log file currently exist so we create a new file
  fs = File::Open(sTestLogFile, FileMode::CreateNew, FileAccess::ReadWrite, 
FileShare::None);
  xmlReport = new XmlDocument();
  XmlDeclaration* xmlDeclaration = xmlReport->CreateXmlDeclaration(S"1.0", 
S"utf-8", NULL);
  // Create the root element
  XmlElement* rootNode = xmlReport->CreateElement("TestLog");
  xmlReport->InsertBefore(xmlDeclaration, xmlReport->DocumentElement);
  xmlReport->AppendChild(rootNode);
  // Create a new <TestResults> element and add it to the root node
  XmlElement* parentNode = xmlReport->CreateElement("TestResults");
  xmlReport->DocumentElement->PrependChild(parentNode);
  parentNode->InnerXml = xmlStr;
}
xmlReport->Save(fs);
fs->Close();
}
catch(XmlException* e)
{
String* msg = e->get_Message();
}
catch(Exception* e)
{
String* msg = e->get_Message();
}
return 0;
}

Output when no file exist GOOD:!

<?xml version="1.0" encoding="utf-8"?>
<TestLog>
  <TestResults>
    <TestResult>
      <Name>Application Load Test</Name>
      <StartTime>21/05/2006 14:45:58:155</StartTime>
      <StopTime>21/05/2006 14:46:35:530</StopTime>
      <TestResult>FAIL</TestResult>
      <TestAtoms>
        <TestAtom>
          <Name>RateTest 1</Name>
          <StartTime>21/05/2006 14:46:20:530</StartTime>
          <StopTime>21/05/2006 14:46:35:530</StopTime>
          <TestResult>FAIL</TestResult>
          <Duration>15</Duration>
          <Direction>0</Direction>
          <MinRate>255</MinRate>
          <MaxRate>255</MaxRate>
        </TestAtom>
      </TestAtoms>
    </TestResult>
  </TestResults>
</TestLog>

Output when file exist (see above) BAD!

<?xml version="1.0" encoding="utf-8"?>
<TestLog>
  <TestResults>
    <TestResult>
      <Name>Application Load Test</Name>
      <StartTime>21/05/2006 14:45:58:155</StartTime>
      <StopTime>21/05/2006 14:46:35:530</StopTime>
      <TestResult>FAIL</TestResult>
      <TestAtoms>
        <TestAtom>
          <Name>RateTest 1</Name>
          <StartTime>21/05/2006 14:46:20:530</StartTime>
          <StopTime>21/05/2006 14:46:35:530</StopTime>
          <TestResult>FAIL</TestResult>
          <Duration>15</Duration>
          <Direction>0</Direction>
          <MinRate>255</MinRate>
          <MaxRate>255</MaxRate>
        </TestAtom>
      </TestAtoms>
    </TestResult>
  </TestResults>
</TestLog><?xml version="1.0" encoding="utf-8"?>
<TestLog>
  <TestResults>
    <TestResult>
      <Name>Application Load Test</Name>
      <StartTime>21/05/2006 14:45:58:155</StartTime>
      <StopTime>21/05/2006 14:46:35:530</StopTime>
      <TestResult>FAIL</TestResult>
      <TestAtoms>
        <TestAtom>
          <Name>RateTest 1</Name>
          <StartTime>21/05/2006 14:46:20:530</StartTime>
          <StopTime>21/05/2006 14:46:35:530</StopTime>
          <TestResult>FAIL</TestResult>
          <Duration>15</Duration>
          <Direction>0</Direction>
          <MinRate>255</MinRate>
          <MaxRate>255</MaxRate>
        </TestAtom>
      </TestAtoms>
    </TestResult>
    <TestResult>
      <Name>Application Load Test</Name>
      <StartTime>21/05/2006 14:45:58:155</StartTime>
      <StopTime>21/05/2006 14:46:35:530</StopTime>
      <TestResult>FAIL</TestResult>
      <TestAtoms>
        <TestAtom>
          <Name>RateTest 1</Name>
          <StartTime>21/05/2006 14:46:20:530</StartTime>
          <StopTime>21/05/2006 14:46:35:530</StopTime>
          <TestResult>FAIL</TestResult>
          <Duration>15</Duration>
          <Direction>0</Direction>
          <MinRate>255</MinRate>
          <MaxRate>255</MaxRate>
        </TestAtom>
      </TestAtoms>
    </TestResult>
  </TestResults>
</TestLog>



0
5/22/2006 6:15:25 AM
dotnet.xml 7266 articles. 0 followers. Follow

4 Replies
873 Views

Similar Articles

[PageSpeed] 21


SteveW wrote:


> FileStream* fs;
> XmlDocument* xmlReport;
> // Test XML Snippet - emulates a test outcome


> String* sTestLogFile = S"D:\\Development\\LogTest\\ResultLog.xml";
> //
> try {
>   if(File::Exists(sTestLogFile) == true) {
>   // file already exist
>   fs = File::Open(sTestLogFile, FileMode::Open, FileAccess::ReadWrite, 
> FileShare::None);
>   xmlReport = new XmlDocument;
>   // Open from Stream
>   xmlReport->Load(fs);

I think the problem is not with the DOM code (e.g. 
XmlDocument.CreateXXX, AppendChild, PrependChild) you use but simply 
with that file stream you use and reuse. Above if the Load call is done 
the stream is read and is subsequently positioned at its very end and 
then when you do

> xmlReport->Save(fs);

the Save call writes to the end of the stream and you will get the 
markup duplicated.
So you need to ensure that your Save call overwrites an existing file 
and does not append to it.

One way to do that would be (pseudo code)

String* sTestLogFile = S"D:\\Development\\LogTest\\ResultLog.xml";
if(File::Exists(sTestLogFile) == true) {

xmlReport = new XmlDocument();
xmlReport.Load(sTestLogFile)
}

xmlReport.Save(sTestLogFile);

so not using any FileStream at all but using the higher level overloads 
of the Load and Save methods which simply take a string with a file name.

-- 

	Martin Honnen --- MVP XML
	http://JavaScript.FAQTs.com/
0
mahotrash (1777)
5/22/2006 2:03:19 PM
Also, it seems that you haven't gotten rid of the problem of the "<?xml
version="1.0" encoding="utf-8"?> " being inserted every time you append
an XML fragment to your file.

0
zorg007 (48)
5/22/2006 2:16:08 PM

Cerebrus wrote:

> it seems that you haven't gotten rid of the problem of the "<?xml
> version="1.0" encoding="utf-8"?> " being inserted every time you append
> an XML fragment to your file.

If he uses the suggestion I made then there will be no duplicated XML 
declaration. Currently his codes safes the complete XML document 
(including the XML declaration and all other nodes) to the end of the 
stream instead of overwriting the same file.


-- 

	Martin Honnen --- MVP XML
	http://JavaScript.FAQTs.com/
0
mahotrash (1777)
5/22/2006 3:12:54 PM
Martin -
Your advice really helped. I use a file stream when the file does not exist 
to create a new file; but when the file does exist, I use the log file path 
to load the XMLDocument as you suggested. This works well and I consider the 
problem resolved. Thanks MVP's for all the good help! I am really interested 
in digging into this more - can anyone recommend a good book that details 
all the various XML methods? I primarily use managed vc++, so something with 
a emphases on vc++ is best.

"Martin Honnen" <mahotrash@yahoo.de> wrote in message 
news:eGun%23hafGHA.1456@TK2MSFTNGP04.phx.gbl...
>
>
> SteveW wrote:
>
>
>> FileStream* fs;
>> XmlDocument* xmlReport;
>> // Test XML Snippet - emulates a test outcome
>
>
>> String* sTestLogFile = S"D:\\Development\\LogTest\\ResultLog.xml";
>> //
>> try {
>>   if(File::Exists(sTestLogFile) == true) {
>>   // file already exist
>>   fs = File::Open(sTestLogFile, FileMode::Open, FileAccess::ReadWrite, 
>> FileShare::None);
>>   xmlReport = new XmlDocument;
>>   // Open from Stream
>>   xmlReport->Load(fs);
>
> I think the problem is not with the DOM code (e.g. XmlDocument.CreateXXX, 
> AppendChild, PrependChild) you use but simply with that file stream you 
> use and reuse. Above if the Load call is done the stream is read and is 
> subsequently positioned at its very end and then when you do
>
>> xmlReport->Save(fs);
>
> the Save call writes to the end of the stream and you will get the markup 
> duplicated.
> So you need to ensure that your Save call overwrites an existing file and 
> does not append to it.
>
> One way to do that would be (pseudo code)
>
> String* sTestLogFile = S"D:\\Development\\LogTest\\ResultLog.xml";
> if(File::Exists(sTestLogFile) == true) {
>
> xmlReport = new XmlDocument();
> xmlReport.Load(sTestLogFile)
> }
>
> xmlReport.Save(sTestLogFile);
>
> so not using any FileStream at all but using the higher level overloads of 
> the Load and Save methods which simply take a string with a file name.
>
> -- 
>
> Martin Honnen --- MVP XML
> http://JavaScript.FAQTs.com/ 


0
5/23/2006 3:00:11 PM
Reply:

Similar Artilces:

Here is fix for Windows file problems
If you have installed a Windows update and started having problems opening, closing, copying files, see: http://www.microsoft.com/communities/newsgroups/list/en-us/default.aspx?dg=microsoft.public.excel.misc&mid=1fe358b1-c8eb-4217-ad2a-4b9fcf741916 A better solution is offered at http://support.microsoft.com/kb/918165 "Problems in Windows Explorer or the Windows shell after you install security update MS06-015". Patricia Shannon wrote: > If you have installed a Windows update and started having problems opening, > closing, copying files, see: > > http://ww...

Fax Icon on my File menu and toolbar
I had a Fax Icon on my toolbar and also on the file menu. All of a sudden it is gone and I want it back. Where did it go? Was it a dedicated toolbar? Or was it just icons on a builtin toolbar? If it was a dedicated toolbar, you may get lucky and find it under: Tools|customize|toolbars tab (just not selected) But if it was on a builtin toolbar (along with the file menu), then maybe you reset your toolbar--also under: Tools|customize|toolbars tab selecting a toolbar and hitting the reset button. If that's what happened, I think I might try to find the Fax addin/workbook that added t...

exporting outlook 2000 pst files to a database
I need to export outlook 2000 to a database- attachments and all. Is there a simple way to do this so you can search and retreive messages and attachments in a database form? Thanks Jeff You can export individual folders to access or excel to have them available for searching. I have never tried to export my entire .pst file to access or excel however. --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. After searching google.groups.com and finding no answer Jeff <laacid@yahoo.com> asked: | I need to export outlook 2000 to a database- ...

office 2000 [excel] cannot open previously OK file. Help
When trying to open a Microsoft Excel Work Sheet that I had accessed modified and saved to only yesterday [Office 2000] a window pops up with: "name.xls cannot be accessed. The file may be resd-only, or you may be trying toaccess a read only location. Or, the server the document is stored on may not be responding." Older files stored on the same mediums ;HD, Flash memory or 3.5in. diskette are accessed with no problem. This is on a network drive? ...

Outlook receiving zip files
Why is it when I try to send zipped files to my address; it gets returned as service unavailable? Hello Omar, your Exchange dont allow you to send this! Please speak with your Domain Admin "Omar" <anonymous@discussions.microsoft.com> schrieb im Newsbeitrag news:0754E7DA-31DC-4966-9FC1-C290A8D8222C@microsoft.com... > Why is it when I try to send zipped files to my address; it gets returned as service unavailable? Hi Omar, your Provider don�t supportet this part of file! -- Gestern lief noch alles, ich habe nichts gemacht! Bitte in der Newsgroup antworten, damit jeder d...

Multiple domains on one Exchange server / All but one domain shows up as spam #2
I am sorry if this is on the board somewhere but I have been searching forever and havn't found a hint yet. I have multiple domains setup on my exchange server. Lets say abc.com, def.com, and hij.com. We only send email with @abc.com but can receive from any domain name. Recently we merged with another company and we brought back their email to our server, lets say xyz.com. Now I configured a new recipient on Exchange 2003, so I now have two policies. The first policy has the three original domains in it with @abc.com as the primary domain. In the second policy I have configured xyz.com t...

VB Macro #2
I have a macro that is generating Excel files. When the macro runs, it saves two different tabs in the workbooks as values. It needs to test and wait until the formulas that are pulling amounts from another database are correctly populated with the amounts. Right now, I am getting N/A# instead of amounts for some, but not all, of the files. I think the problem is that the formulas have not completed pulling the amounts before the macro pastes that tab as zeros. (N/A# is what appears when the formulas have not completed calculating - once they have completed, the N/A# is replaced ...

unable to read file #7
Does anyone know how to solve this error? This is the second time I have had the same error on the same file. Last time I was able to recover from a saved copy and updated fine. This time whenI opened the copy and updated it, then saved it, I got the same error when I tried to open it again, Now I don't have a good copy. I have downloaded all avaliable updates and tried running "Excel.exe /regserver>ok" This did not help. I also ran defran on the drive. "Randell" wrote > Does anyone know how to solve this error? This is the > second time I have had th...

VCR to DVD Part 2
Many thanks for previous answers. Yes, finalizing the DVD worked I found that DVD-R need finalizing but DVD+RW disks do not But why was I able to play the unfinalized DVD-R on one machine and not on two others. What was special about the first PC? -- www.stfx.ca/people/bliengme Bernard Liengme wrote: > Yes, finalizing the DVD worked > I found that DVD-R need finalizing but DVD+RW disks do not > But why was I able to play the unfinalized DVD-R on one machine and not on > two others. > What was special about the first PC? Almost anything will play a finalised D...

SBS 2003 moving of users files
I run SBS 2003 and due to the amount of data on the users drive it has become chokers and have installed a new 1tb drive to keep up with demand for space. I need to move all the data to the new drive but unsure of the process. Is there an easy way of doing this? As it needs to be done asap Thanks -- JimmyJames ------------------------------------------------------------------------ JimmyJames's Profile: http://forums.techarena.in/members/255792.htm View this thread: http://forums.techarena.in/small-business-server/1357051.htm http://forums.techarena.in You c...

Importing AOL Email File Cabinet
Is it possible to tranfer a complete AOL Email File Cabinet into outlook? AFAIK, no, but see if anything here will do it: http://www.slipstick.com/config/convmsg.htm - check out Address Magic Plus first, it can convert almost anything. -- Diane Poremsky [MVP - Outlook] Need Help with Common Tasks? http://www.outlook-tips.net/beginner/ Outlook 2007: http://www.slipstick.com/outlook/ol2007/ Outlook Tips by email: dailytips-subscribe-request@lists.outlooktips.net EMO - a weekly newsletter about Outlook and Exchange: EMO-NEWSLETTER-SUBSCRIBE-REQUEST@PEACH.EASE.LSOFT.COM Outlook Tips: http:/...

Searching on date strings
Version: 2008 Operating System: Mac OS X 10.5 (Leopard) Processor: Intel I want to create a simple 2-row Gantt chart that compares dates in a column, 11-rows long with a date range across the top and populate the cells underneath the dates with a set of task #s that match the rows. For example if the first 3 tasks are all scheduled in Week 1, the cell under that date would show: &quot;1,2,3&quot;. <br><br>Other than an 11-nested 'IF' function, is there an easier way to do this? Not that I know of. You might have a look at a Pivot Table and see if you can ...

set print area #2
Where is the "set print area" button in Excel 2002 that was in Excel '97? =?Utf-8?B?Q2Fyb2wgTWM=?= wrote > Where is the "set print area" button in Excel 2002 that was in Excel '97? > Are you sure it was "standard"? Only way I could get in was to right-click the toolbar|Customise and drag it to the toolbar from Commands|File -- David ...

a few basic question about resource files
Hi, I have an application that uses resource files to contain the string values for each language. I have created the required resource files in my project, but I don't speak the languages I wish to have resources for. What I would like to do, is somehow allow the end user to edit the resource file themselves so they can set the string values as needed. Is there a way to edit the resource files that ship with my application and get installed ? or Is there a way to have external resource files (not embedded into my application) that can be updated/replaced with o...

Exporting contacts in a csv file
I am a mysterious problem exporting my contacts as csv file. The resulting file has only 58 contacts out of almost 1200 contacts in my outlook. These contacts appear to be the last 58 contacts added. (I say appear because the attribute "createdon" is not exported so I can't be exact. Why is this? cinnamngrl <cinnamngrl@gmail.com> wrote: > I am a mysterious problem exporting my contacts as csv file. The > resulting file has only 58 contacts out of almost 1200 contacts in my > outlook. These contacts appear to be the last 58 contacts added. (I > say appea...

is there a way to program my Excel file to do a loop?
Hi all, If I want B10 to B17 all follow the change of the same number(copy cell), let's say I put it in A1, and C10 follows the change of A2(copy cell), and C11 follows the change of A3(copy cell), and C12 follows the change of A4(copy cell), then I have 4 variables in my calculations: A1, A2, A3, A4. I want to loop each of the variables in a different set, then I hope the whole worksheet will be able to refresh following the change of A1, A2, A3, A4, and then I want to find the very set of A1, A2, A3, A4 that gives the smallest value of D10, how do I program the whole procedure...

Publisher can not save file
I recently started having troubles with my Publisher 2003. Whenever I go to save my files now, using save as or just the save button, it gives me a dialog box that says "Can not save file." It does that twice, then it disappears. I also noticed that when it does this, it leaves the .tmp files in the directory where I tried to save. I can change the name of the files, and sometimes it will save it. Most of the time not though. I have NAV, and I noticed that it was said there was an issue with Publisher and NAV. Is this the same with the 2005 version, and is this anything anyone...

Excel 2007 PC damages Mac Excel 2008 Files
Version: 2008 Operating System: Mac OS X 10.4 (Tiger) Processor: Intel When I open a Mac Excel 2008 file on Excel 2007 and I can work with the file, however when the file is returned to the Mac, it no longer works correctly, leading to a crash as soon as I try to save or eventually it might change the file to look like a bunch of letters and characters. Here is the error report: <br><br>Microsoft Error Reporting log version: 2.0 <br><br>Error Signature: <br> Exception: EXC_BAD_ACCESS <br> Date/Time: 2010-01-15 17:05:56 -0600 <br> Application N...

OEM publisher 2002 Sp1-2
I have the OEM version of Publisher 2002 and cannot find the Export as web page under File. Is there a way I can get that feature with a standalone disk? After managing to set up OE-QuoteFix on his new PC, Ed reads a message from Chicagogal <anonymous@discussions.microsoft.com>... > I have the OEM version of Publisher 2002 and cannot find the Export > as web page under File. Is there a way I can get that feature with a > standalone disk? The OEM version of Publisher is exactly the same as the release in every way but the license, so the standalone version will be no differen...

140 MB file went to 5.08 MB after editting 1 table
Hello All - I need some ACCESS insight...please... Several years ago, I built an access db to track my business scheduling and accounts payable/receivable. So this database is EXTREMELY IMPORTANT TO ME. The file has grown to 140 MB. Today I made a copy of the file and then edited my calendar table. I removed all columns which had 2006 data (72 totals columns) - the table had about 144 columns originally. I then added 72 columns with 2008 headers. These columns are now blank since I have not added any 2008 data yet. Afterwards, I looked around and everything looks good - my 2007 data is the...

GP SP#2 hangs with sa and Collections Issue
I just installed 8.0 SP#2 (ran the script that it says to run cuz we had upgraded from previous version to remove dups in smartlist tables) and when I log into GP as sa, it hangs and CPU sits at 100%. When I was able to log in previously to SP#2, I constantly received errors about the CN_Collector_MAIN table with invalid column names etc. I've deleted the table, then re-ran the create tables, but it keeps coming back with this error. I've even gone into file > maintenance > sql and deleted and recreated the table, but then get "number of results doesn't match ...

Exchange server crashed, please help....! Need to restore two priv.edb and pub.edb files into one....!
Hi Guys, I was wondering if I could get some help with the following problem we are having on our company. Here is the scenario; Our Windows NT 4.0 SP4a server running Exchange 5.5 SP4 crashed (Server 1) due to the exchange database reaching its 16 Gig's max limit. I went ahead and moved some mailboxes' e-mails to a few .pst files in order to make some space. This worked ok. Then, I decided to build another exchange server (Server 2) to moved some mailboxes and alleviate the load. Once the server was ready and configured as part of the current exchange site, I went ahead and move...

pulling certain characters from a string of text
I need to look up "certain critera" within a string of characters, then return that "certain criterea" to a new column. Some examples of a strings of characters may look like these: K5J091509001 Sample PO#S881009 K55sample PO CarrieRJR TJ5 My "Certain Critera" I have listed on another sheet, named "REP ID" K5J S88 K55 RJR TJ5 How do I pull out the 3 characters of "Certain Criterea" from the string of text and copy or enter it into a new column? Hi, =left(a1,3) "SaraMack" wrote: > I need to look up "c...

XML selectsinglenode
Hi I have an XML file i need to load and read the contents. Here is the top part of the xml file. <Research xsi:schemaLocation="http://www.rixml.org/2002/6/RIXML http://GreenJAR/DAVCatalog/Dashboards/GreenJAR/Documents/Schemas/RiXML2.xsd" researchID="" createDateTime="2003-07-10T00:00:00" language="eng" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.rixml.org/2002/6/RIXML"> <Product productID="BJZABULLETIN_0711" eventIndicator="No" sequence="0"> <StatusInfo sta...

Error loading XML into DataSet
Hello, When I try to load this xml file (see below) into an asp.net dataset using the following code: ds.ReadXml("xmlfilepath\xmlfile.xml", XmlReadMode.Auto) I get the following error: "The same table (description) cannot be the child table in two nested relations. " If I take out the anchor tag in the description it works fine, however, I need the anchor tag in there. Does anyone have any suggestions? <?xml version="1.0" ?> <rss version="2.0"> <channel> <title>Liftoff News</title> <link>http://liftoff.msf...