views:

98

answers:

1

I've got three problems with some data that I'm serializing.

First off, it outputs <?xml version="1.0" encoding="utf-8"?> but the program that I'm loading it into only wants <?xml version="1.0"?>

Secondly, whenever the data is empty it will use shorthand for closing the tag (<z303-profile />) but the program that I'm loading it into won't accept that and requires <z303-profile></z303-profile>

Lastly, I have some data that I can't guarantee how long it will be so I have it in a List. I need each of the items to have their own heading of z305, but it outputs the name of the list that they're being held in first which messes everything up. It's being displayed as follows

    <z305List>
      <z305>
        ....
      </z305>
      <z305>
        ....
      </z305>
    </z305List>

with the list being stored as

[XmlArrayItem("z305")]
public List<LocalPatronInfo> z305List = new List<LocalPatronInfo>();

The code I'm using for serialization is as follows

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer xmls = new XmlSerializer(typeof(AllRecords));
TextWriter tw = new StreamWriter(richTextBoxWorkingDir.Text + "\\" + filename);
xmls.Serialize(tw, allRecords, ns);
tw.Close();
+1  A: 

I think I've found the solution to first two problems with my third attempt. Advice was of course on this site (where else can it be? :-P) :

XmlSerializer uses XmlWriter to write XML. So when you make you own XMlWriter.. almost everything is possible. Please look at the following code:

public class XmlTextWriterFull : XmlTextWriter
{
    public XmlTextWriterFull(TextWriter sink) : base(sink) { }

    public override void WriteEndElement()
    {
        base.WriteFullEndElement();
    }

    public override void WriteStartDocument()
    {
        base.WriteRaw("<?xml version=\"1.0\"?>");
    }
}

public class temp
{
    public int a = 0;
    public List<int> x = new List<int>();
}

class Program
{
    static void Main(string[] args)
    {
        XmlTextWriterFull writer = new XmlTextWriterFull(Console.Out);

        XmlSerializer xs = new XmlSerializer(typeof(temp));
        xs.Serialize(writer,new temp());
        Console.ReadKey();
    }
}
Bart
Very nice! This clears up all the issues but leaves everything on the same line instead of nicely indented. Once I changed the XmlTextWriterFull constructor to use "this.Formatting = Formatting.Indented;" the empty end elements ended up on a new line. Not a big deal for me since they give me a "null character" to work with. At least now I don't have to read the 250 meg file back in just to change one line anymore. Thanks again!
Califer
I'll look at it later, I think it also can be done in some way. Thanks for great question. Trying to solve it was really interesting and I also learn something new about XmlSerializer. Despite some minor disadvantages I like this method of generating XMLs a lot and use frequently.
Bart