473,805 Members | 1,995 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem appending a new element to xml file...

Hi all,

I'm trying to distill all of the info from google searches into what I
need, with partial success. In truth, the whole xmlNode, Document,
Element, etc group of classes & methods is going over my head - lol!

The structure of the xml file I'm trying to append to is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!-- stuff -->
<!-- more stuff -->
<Scenarios attr="0">
<Scenario num="0">
<TimeSeries name="cdj" >
<Observation date="01/01/2001" value="1000"/>

a whole bunch more observations

</TimeSeries>
</Scenario>
</Scenarios>

I'm trying to code up a routine that adds another Observation to the
list. Here's what I've got:

public void WriteHistory(Hi storyType histype, double val)
{
try
{
XmlDocument cdjDoc = new XmlDocument();
XmlNode parentNode;

cdjDoc.LoadXml( monthlyPath + filename);
parentNode = cdjDoc.Document Element;

XmlNode newElement = cdjDoc.CreateNo de(XmlNodeType. Element,
"Observatio n", null);
cdjDoc.AppendCh ild(newElement) ;

XmlAttribute date = cdjDoc.CreateAt tribute("date") ;
date.InnerText = DateTime.Now.To String("MM/dd/yyyy");
newElement.Attr ibutes.Append(d ate);

XmlAttribute rate = cdjDoc.CreateAt tribute("value" );
rate.InnerText = val.ToString();
newElement.Attr ibutes.Append(r ate);

XmlTextWriter writer = new XmlTextWriter(m onthlyPath +
filename,null);
cdjDoc.Save(wri ter);
}
catch(Exception ex)
{
MessageBox.Show (ex.Message,"Sc rewed!");
}

This doesn't work - throws an exception with message:

The data at the root level is invalid. Line 1, position 1.

I believe the problem is that I'm not "finding" the proper spot in the
xml structure to AppendChild my new element to. Can someone help me
with this? (Or any other problem, if I'm mistaken in my diagnosis?)

Thanks for any guidance,

cdj

Nov 16 '06 #1
13 2621
You're making it very hard on yourself.

Try this (and note than most of the "code" is the XML block to make it
demonstrable); I have also used a more exotic query in SelectSingleNod e
than is probably necessary... depends if you need to select a
*specific* scenario/series; if only one you can drop all the
[@something='val ue'] stuff...

using System;
using System.Xml;
class Program {
static void Main()
{
const string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>

<Scenarios attr=""0"">
<Scenario num=""0"">
<TimeSeries name=""cdj"" >
<Observation date=""01/01/2001"" value=""1000""/>
<Observation date=""02/02/2001"" value=""2000""/>
<Observation date=""03/03/2001"" value=""3000""/>
</TimeSeries>
</Scenario>
</Scenarios>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml ); //TODO: doc.Load(filena me);
XmlElement el = (XmlElement)
doc.SelectSingl eNode(@"Scenari os[@attr='0']/Scenario[@num='0']/TimeSeries[@name='cdj']");
XmlElement newObservation =
(XmlElement)el. AppendChild(doc .CreateElement( "Observation")) ;
newObservation. SetAttribute("d ate",
DateTime.Today. ToString("MM/dd/yyyy"));
newObservation. SetAttribute("v alue",
DateTime.Today. ToString("3000" ));

Console.WriteLi ne(doc.OuterXml ); //TODO: doc.Save(filena me);
}
}

Nov 16 '06 #2

Marc Gravell wrote:
You're making it very hard on yourself.
Hey! I'm tryin here!

lolol! Just teasin - thanks - I'll give it a whirl!

cdj

Nov 16 '06 #3
Actually, I note your example hints at another level of xml nodes (not
shown)... in which case either include this in the XPath/XQuery, or
replace doc.SelectSingl eNode(...) with
doc.DocumentEle ment.SelectSing leNode(...), which will take you inside
the outer element.

Marc

Nov 16 '06 #4

Marc Gravell wrote:
Actually, I note your example hints at another level of xml nodes (not
shown)... in which case either include this in the XPath/XQuery, or
replace doc.SelectSingl eNode(...) with
doc.DocumentEle ment.SelectSing leNode(...), which will take you inside
the outer element.

Marc
As the example structure I gave indicates, it is theoretically possible
for there to be multiple X's within a given Y for a variety of Y's.

In actual fact, the only case of interest to what I need is the
multiple Observations within a TimeSeries. Or to put it equivalently (I
hope): Observations are the only nodes with siblings.

Thanks again!

cdj

Nov 16 '06 #5
Glad to help - any problems, be sure to get back...

For completeness: your original code touched on XmlWriter; this is
typically used *instead of* the XmlDocument model in those scenarios
where XmlDocument is too heavy - just as very large xml fragments; with
XmlWriter you could write a 500Mb file from a database by writing one
row at a time directly to hte stream; with the XmlDocument you would
need to hold it all in memory first, probably taking about 4-times
that, so 2Gb (better hope for Win64 memory addressing!).
XmlDocument, however, uses the "all in memory" model to provide
services such as XPath/XQuery, and simple element manipulation. There
are other differences, but that is the general principle; for
small-to-mid-size xml, XmlDocument is a reasonable choice.

Marc

Nov 16 '06 #6

Marc Gravell wrote:
Glad to help - any problems, be sure to get back...

For completeness: your original code touched on XmlWriter; this is
typically used *instead of* the XmlDocument model
The biggest problem I'm having now is preserving all of the pretty
tabs/formatting in the xml document. The PreserveWhiteSp ace property
does better than nothing, but falls substantially short of what might
be expected. For example, even with PreserveWhiteSp ace, a newline is
*not* inserted after the new Observation is added - this surprises me.

Is there a straightforward way to maintain the tab/newline structure?
(It's intuitively obvious what structure I'm talking about - tabs to
indicate hierarchy-level-descent, newlines for new elements.)

You brought up a new issue to me: the xmlDocument vs XmlWriter. The
code I've been working with, per your suggestion (I thought - lol) is:

XmlDocument cdjDoc = new XmlDocument();
cdjDoc.Preserve Whitespace = true;

XmlTextReader reader = new XmlTextReader(m onthlyPath + filename);
cdjDoc.Load(rea der);
reader.Close();

XmlElement el =
(XmlElement)cdj Doc.SelectSingl eNode(@"Scenari os[@version='1']/Scenario[@id='0']/TimeSeries[@name='cdj']");
XmlElement newObservation =
(XmlElement)el. AppendChild(cdj Doc.CreateEleme nt("Observation "));
newObservation. SetAttribute("d ate",
DateTime.Today. ToString("MM/dd/yyyy"));
newObservation. SetAttribute("v alue", val.ToString()) ;

XmlTextWriter writer = new XmlTextWriter(m onthlyPath +
filename,null);
cdjDoc.Save(wri ter);
writer.Close();

Is there a better way to load/save the xml file to/from disk besides
this? Do tell. lol

thanks again!

cdj

Nov 16 '06 #7

sherifffruitfly wrote:
Marc Gravell wrote:
Glad to help - any problems, be sure to get back...

For completeness: your original code touched on XmlWriter; this is
typically used *instead of* the XmlDocument model

The biggest problem I'm having now is preserving all of the pretty
tabs/formatting in the xml document.
Nevermind on the prettyprinting. The following lines, in the right
place, completely suffice for me:

cdjDoc.CreateNo de(XmlNodeType. Text, "\n", null);

writer.Formatti ng = Formatting.Inde nted;
writer.Indentat ion = 4;

Thanks for your previous help tho!

cdj

Nov 17 '06 #8
I was going to suggest:

XmlWriterSettin gs settings = new XmlWriterSettin gs();
settings.Indent = true;
settings.NewLin eHandling = NewLineHandling .Entitize;
using (Stream fs = File.OpenWrite( @"c:\out.xml "))
using (XmlWriter writer = XmlWriter.Creat e(fs, settings))
{
doc.Save(writer );
writer.Close();
fs.Close();
}

I guess either route achieves the same...

Marc

Nov 17 '06 #9
Or (shorter)

XmlWriterSettin gs settings = new XmlWriterSettin gs();
settings.Indent = true;
settings.NewLin eHandling = NewLineHandling .Entitize;
using (XmlWriter writer = XmlWriter.Creat e(@"c:\out.xml" ,
settings))
{
doc.Save(writer );
writer.Close();
}

Nov 17 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2276
by: Fnark! | last post by:
I am creating a shopping cart using PHP Version 4.1.2. I am creating and registering a cart object in a session. The cart object contains an array of arrays called $order whose elements are a collection of $orderline associative arrays which, in turn, hold the global POST values key 'order_code' and value 'qty' as passed in from another page. My problem is (shown by using print_r to print out the contents of the arrays) each time I...
1
2453
by: Jonathan Taylor | last post by:
I have a large XML file, that is too large to read in to XmlDocument. I need to append data to this XML file without creating a new file, since I don't want to have two copies of the large file on the server. I've not seen any example that works so far, even with google. Can anyone help ?
2
3601
by: Cat | last post by:
How do you go about appending data from a dataset to an existing xml file? I know you can use WriteXML but this writes over any data already existing in the specified file.. Cat
1
2304
by: Ron Adam | last post by:
In my program I have a lot of statements that append elements, but sometimes I don't want to append the element so it requres an if statement to check it, and that requires assigning the returned element from a function to a name or calling the funtion twice. e = ET.Element('name') e.append(get_subelement(obj)) # but raises an exception on None
3
565
by: Jim | last post by:
Could anyone please point me towards some code that allows me to add to an existing XML file using the output of an HTML form. I want to add a form on my website so users can input their email address in a text field and feedback in a text area and then submit it. I can output the data no probs but appending it first to the XML file is proving tricky. Any ideas?
2
3718
by: Emmanuel | last post by:
I am writing java application which will store data in XML file..Each time when i execute that program ,previous data will be overidden.. Is it possible to append data to XML file,if anybody knows please assist me
5
10045
by: =?Utf-8?B?SmVmZiBCZWVt?= | last post by:
Before you respond with "just use GetShortPathName" please read the rest. We have an application that places files on a file server using mapped drives as it's path of choice. The reason for this is because using a UNC paths makes the path longer, causing the periodic problem with a path that is too long (over 260 chars). We also have an asp.net app that needs to access those files. Accessing mapped drives from an IIS application is...
1
3793
by: ofuuzo1 | last post by:
Hi, Is there anyway I can append a new element to an existing xml without first loading the existing file into a variable, adding the new element into the variable and saving it by overwriting the existing file name? Thanks Ofuuzo
1
3981
by: bkamrani | last post by:
Hi Python gurus, I have installed numpy and interested in testing f2py module using the first example in the documentation. First I tried: C:\test>python "C:\Program Files\Python25\Scripts\f2py.py" -c fib1.f running build running config_cc unifing config_cc, config, build_clib, build_ext, build commands --
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10607
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10359
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9182
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7645
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5541
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4317
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.