Ege Bayrak
Ege Bayrak

Reputation: 1199

XML Parsing Error: no element found message and empty document creation

I'm trying to create an xml file. I already set the document and have a result with Xmlwriter when printing to console but when it comes to having an actual .xml file on my desktop I always end up with empty files. Clearly I'm missing something or forgetting something but can't tell on my own.

Below is the piece of my code where it all happens (not).

public void button1_Click(object sender, EventArgs e)
    {
        XmlDocument dddxml = new XmlDocument();

        //XmlDeclaration xmldecl;
        //xmldecl = dddxml.CreateXmlDeclaration("1.0", null, null);
        //xmldecl.Encoding = "UTF-8";
        //xmldecl.Standalone = "yes"; 

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Encoding = Encoding.UTF8;
        settings.Indent = true;


        StringBuilder builder = new StringBuilder();


        writer = XmlWriter.Create(builder, settings);

        writer.WriteStartDocument();
        writer.WriteStartElement("root");
        BlockSelect(0);

        writer.WriteEndElement();
        writer.WriteEndDocument();

        writer.Close();


        Console.WriteLine(builder.ToString());

        writer = XmlWriter.Create("DddXml.Xml", settings);
        dddxml.Save(writer);
        File.Create(path);//declared elsewhere, valid file location string
    }

Upvotes: 0

Views: 2117

Answers (3)

Neyoh
Neyoh

Reputation: 633

If you want you can also use LINQ, it's easier :

XDocument doc = new XDocument();
XNamespace ns = "";
doc.Add(new XElement(ns + "root"));
doc.Save(@"C:\DddXml.Xml");

Upvotes: 1

Joel Legaspi Enriquez
Joel Legaspi Enriquez

Reputation: 1236

As commented by @Charles Mager, File.Create() just makes an empty file.

You can try to write directly to the file instead of using StringBuilder. Here's a sample to directly write to the file using the XmlWriter:

 XmlWriter writer = XmlWriter.Create("C:\\ddxml.xml", settings);
 writer.WriteStartDocument();
 writer.WriteStartElement("root");
 writer.WriteEndElement();
 writer.WriteEndDocument();
 writer.Close();

See that the file is written on C:\ddxml.xml.

Upvotes: 2

Andrey Korneyev
Andrey Korneyev

Reputation: 26856

You have created new XmlDocument here:

XmlDocument dddxml = new XmlDocument();

But you haven't populated it in the rest of the code and in fact you're not using it and writing xml to string builder using WriteStartDocument and WriteEndElement methods of XmlWriter.

Thus your dddxml remains empty, so when you're trying to save it like this:

dddxml.Save(writer);

, there is nothing to save and you're getting empty file.

So you have to choose - will you use XmlDocument or XmlWriter to create and save your xml.

Upvotes: 2

Related Questions