Reputation: 21
I'm looking for some help.
I created an mp3
web service using visual studio c# and xml
to store the data. I created a method that will allow a user to create a new playlist id to be stored to the xml
document. I set my xml
file as follows:
public class Service : System.Web.Services.WebService
{
//used as an access path to the xml file
string xmlFileName = "F:\\WebServices\\Mp3Server\\SongList.xml";
This is before any of the methods in my program.
My songlist.xml
file is stored correctly and is the correct path from what I can see.
I currently had mp3
id's stored on the songlist.xml
file is as follows:
<Playlist ID="123">
<Song Title="Bump">
<Artist>Ed Sheeran</Artist>
<Album>Asylum</Album>
<Year>2011</Year>
<Genre>Folk</Genre>
</Song>
<Song Title="3 AM">
<Artist>Matchbox Twenty</Artist>
<Album>Exile On Mainstream</Album>
<Year>2007</Year>
<Genre>Rock</Genre>
</Song>
</Playlist>
The code I wrote to create a new playlist id is as follows:
//creates a new playlist
[WebMethod]
public string createPlaylistName(string playlistID)
{
string errorMessage = "";
List<string> playlistNames = createPlaylist("/SongList//Playlist/ID");
if (playlistNames.Contains(playlistID))
{
errorMessage = "error! Id already exists";
}
else
{
string xpath = "/SongList/Playlist[@ID'" + playlistID + "']";
XmlDocument doc = new XmlDocument();
doc.Load(xmlFileName);
XmlElement root = doc.DocumentElement;
XmlNode playistNode = root.SelectSingleNode(xpath);
XmlElement playList = doc.CreateElement("Playlist");
XmlAttribute ID = doc.CreateAttribute("ID");
ID.Value = playlistID;
playList.Attributes.Append(ID);
playistNode.InsertAfter(playList, playistNode.LastChild);
doc.Save(xmlFileName);
errorMessage = "success";
}
return errorMessage;
}
But when I run the program, create a new playlist Id and invoke the command: it displays "page not found" webpage.
I can't figure out why the create method is crashing.
If anyone can give any advice, I would appreciate it very much.
Upvotes: 0
Views: 33
Reputation: 26233
Have you tried stepping through it? You'll find that it fails because your XPath expression isn't valid. Your concatenation creates an expression like this:
/SongList/Playlist[@ID'123']
Where it should be:
/SongList/Playlist[@ID='123']
I'm also not entirely sure the logic makes sense. You're checking that a playlist doesn't exist with that ID and then adding one. So how is your XPath expression supposed to return an element?
As an aside, you should probably look into LINQ to XML - it's a much nicer API, for example:
var doc = XDocument.Load(xmlFileName);
var playlist = doc.Descendants("Playlist")
.Single(e => (string)e.Attribute("ID") == "123");
playlist.AddAfterSelf(
new XElement("Playlist",
new XAttribute("ID", "456")
));
Upvotes: 1