lyubolp
lyubolp

Reputation: 349

C# Xml - Invalid name character; The ' ' character cannot be included in a name

So Im making a music player in C#. When a user opens a song, i want it to be saved to a xml file (it saves its path, its name and its duration). Whenever I try to send the value to the library that does the saving I get this error.

MusicLibraryWriter.DatabaseWriter+MyException: System.ArgumentException: Invalid name character in 'Song file path'. The ' ' character, hexadecimal value 0x20, cannot be included in a name.

Here is my code:

    public string addToDatabasedataBaseInfo( songInfo dataToWrite)
    {
        try
        {

            string newSongPath = dataToWrite.songFilePath;
            XmlWriter databaseWriter = XmlWriter.Create("databaseEdit.xml");
            databaseWriter.WriteStartDocument();
            databaseWriter.WriteStartElement("Songs");
            databaseWriter.WriteElementString("Song file path", newSongPath);
            databaseWriter.WriteElementString("Song duration", dataToWrite.songDuration.ToString());
            databaseWriter.WriteEndElement();
            databaseWriter.WriteEndDocument();
            databaseWriter.Close();
            //databaseWriter.Dispose ();

            mergeDataBase();


            return "Success";
        }
        catch (Exception e)
        {
            throw new MyException(e.ToString());

        }
    }

Upvotes: 1

Views: 6628

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504182

This is the problem:

databaseWriter.WriteElementString("Song file path", newSongPath);

You're trying to create an element with a name of Song file path, and that's not valid in XML. Element names can't contain spaces. You could use something like:

databaseWriter.WriteElementString("SongFilePath", newSongPath);

(You'll need to do the same thing for the duration, of course.)

Note that although in this case your code is reasonably simple, for more complicated XML you'd probably be better off building up an XDocument and then saving that to disk. Also, you should use a using statement for your writer, so it's disposed automatically even if there's an exception. (You can then remove the Close call.)

Also note that despite your method name implying that it will add an entry, it's actually going to replace the file completely with just the single song in it.

Finally, you should follow .NET naming conventions, naming your methods and types in PascalCase (leading capital letter).

Upvotes: 4

Related Questions