【问题标题】:Issue with Xml ProjectXml 项目的问题
【发布时间】:2015-07-09 09:32:50
【问题描述】:

我正在寻求帮助。

我使用 Visual Studio C# 和 xml 创建了一个 mp3 Web 服务来存储数据。我创建了一个方法,允许用户创建一个新的播放列表 ID 以存储到 xml 文档中。我将我的xml 文件设置如下:

public class Service : System.Web.Services.WebService
{
    //used as an access path to the xml file
    string xmlFileName = "F:\\WebServices\\Mp3Server\\SongList.xml";

这是在我的程序中的任何方法之前。

我的songlist.xml 文件存储正确,并且是我所看到的正确路径。

我目前将mp3 id 存储在songlist.xml 文件中如下:

<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>

我编写的用于创建新播放列表 id 的代码如下:

//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;
}

但是当我运行程序时,创建一个新的播放列表 ID 并调用命令:它显示“找不到页面”网页。

我不知道为什么 create 方法会崩溃。

如果有人可以提供任何建议,我将非常感激。

【问题讨论】:

  • 您是否尝试过添加断点来查看代码中的具体问题所在?

标签: c# xml web-services


【解决方案1】:

您是否尝试过单步执行?您会发现它失败了,因为您的 XPath 表达式无效。您的串联会创建如下表达式:

/SongList/Playlist[@ID'123']

它应该在哪里:

/SongList/Playlist[@ID='123']

我也不完全确定逻辑是否合理。您正在检查具有该 ID 的播放列表,然后添加一个。那么你的 XPath 表达式应该如何返回一个元素呢?

顺便说一句,您可能应该研究一下 LINQ to XML - 它是一个更好的 API,例如:

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")
        ));

【讨论】:

  • 谢谢大家,我想通了,得到了我想要的工作。
猜你喜欢
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 2011-10-23
相关资源
最近更新 更多