tags:

views:

160

answers:

8

I am storing logs in an xml file...

In a traditional straight text format approach, you would typically just have a openFile... then writeLine method...

How is it possible to add a new entry into the xml document structure, like you would just with the text file approach?

A: 

use an XmlWriter.

example code:

    public class Quote
    {
        public string symbol;
        public double price;
        public double change;
        public int volume;
    }


    public void Run()
    {
        Quote q = new Quote
            {
                symbol = "fff",
                price = 19.86,
                change = 1.23,
                volume = 190393,
                };
        WriteDocument(q);
    }



    public void WriteDocument(Quote q) 
    {
        var settings = new System.Xml.XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                Indent= true
            };

        using (XmlWriter writer = XmlWriter.Create(Console.Out, settings))
        {
            writer.WriteStartElement("Stock");
            writer.WriteAttributeString("Symbol", q.symbol);
            writer.WriteElementString("Price", XmlConvert.ToString(q.price));
            writer.WriteElementString("Change", XmlConvert.ToString(q.change));
            writer.WriteElementString("Volume", XmlConvert.ToString(q.volume));
            writer.WriteEndElement();
        }
    }

example output:

<Stock Symbol="fff">
  <Price>19.86</Price>
  <Change>1.23</Change>
  <Volume>190393</Volume>
</Stock>

see Writing with an XmlWriter for more info.

Cheeso
-1 for not implementing a using block and for not using XmlWriter.Create.
John Saunders
If you reach the Close, it means no exception occurred. The using will call Dispose even if an exception occurred. You're getting there. You'll get an upvote from me quite soon, I expect.
John Saunders
+1  A: 

The big difference is the way you are thinking about your log data. In plain text files you are indeed just adding new lines. XML is a tree structure however, and you need to think about like such. What you are adding is probably another NODE, i.e.:

<log>
   <time>12:30:03 PST</time>
   <user>joe</user>
   <action>login</action>
<log>

Because it is a tree what you need to ask is what parent are you adding this new node to. This is usually all defined in your DTD (Aka, how you are defining the structure of your data). Hopefully this is more helpful then just what library to use as once you understand this principle the interface of the library should make more sense.

Scanningcrew
A: 

Without more information on what you are doing I can only offer some basic advice to try.

There is a method on most of the XML objects called "AppendChild". You can use this method to add the new node you create with the log comment in it. This node will appear at the end of the item list. You would use the parent element of where all the log nodes are as the object to call on.

Hope that helps.

Jason
A: 

XML needs a document element (Basically top level tag starting and ending the document). This means a well formed XML document need have a beginning and end, which does not sound very suitable for logs, where the current "end" of the log is continously extended.

Unless you are writing batches of self contained logs where you write everything to be logged to one file in a short period of time, I'd consider something else than XML.

If you are writing a log of a work-unit done, or a log that doesn't need to be inspected until the whole thing has finished, you could use your approach though - simply openfile, write the log lines, close the file when the work unit is done.

nos
+5  A: 

Use a logging library that does that kind of stuff out of the box.

JP Alioto
A: 

Why reinvent the wheel? Use TraceSource Class (System.Diagnostics) with the XmlWriterTraceListener.

John Saunders
A: 

For editing an xml file, you could also use LINQ. You can take a look on how here: http://www.linqhelp.com/linq-tutorials/adding-to-xml-file-using-linq-and-c/

julio.g
A: 

One of the problems with writing a log file in XML format is that you can't just append lines to the end of the file, because the last line has to have a closing root element (for the XML to be valid)

This blog post by Filip De Vos demonstrates quite a good solution to this:
High Performance writing to XML Log files

Basically, you have two XML files linked together using an XML-include thing:

Header file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log [
<!ENTITY loglines SYSTEM "loglines.xml">
]>
<log>
&loglines;
</log>

Lines file (in this example, named loglines.xml):

<logline date="2007-07-01 13:56:04.313" text="start process" />
<logline date="2007-07-01 13:56:25.837" text="do something" />
<logline date="2007-07-01 13:56:25.853" text="the end" />

You can then append new lines to the 'lines file', but (most) XML parsers will be able to open the header file and read the lines correctly.

Filip notes that: This XML will not be parsed correctly by every XML parser on the planet. But all the parsers I have used do it correctly.

codeulike