【问题标题】:Parsing Xml via XPath gives error通过 XPath 解析 Xml 会出错
【发布时间】:2014-10-09 01:44:05
【问题描述】:

我有一个使用 XmlDocument 类加载的非常简单的 xml 字符串。现在我试图通过 XPath 查询读取它,我收到了这个错误,

“表达式必须计算为节点集。”

这是我的 Xml,

<RF_SearchTermBanners>
   <ImageName>3pc-leather-set.jpg</ImageName>
</RF_SearchTermBanners>

这是我的 C# 代码,

protected void BindSearchBanner(string ImageUrl)
{
    //Parse Xml string containing Image name
    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
    xmlDoc.LoadXml(ImageUrl);

    System.Xml.XmlNode node = (System.Xml.XmlNode)xmlDoc.DocumentElement;
    System.Xml.XmlElement imageElem = node.SelectSingleNode("@/RF_SearchTermBanners/ImageName") as System.Xml.XmlElement;

    string imgUrl = imageElem.InnerText;

    if (imgUrl != null && imgUrl != string.Empty)
    {
        SearchBanner.ImageUrl = "~/Themes/Default/Images" + imgUrl;
        SearchBanner.Visible = true;
    }
    else
    {
        SearchBanner.ImageUrl = string.Empty;
        SearchBanner.Visible = false;
    }
}

请帮忙。

【问题讨论】:

  • 代码 LoadXml(ImagePath) 看起来很奇怪。您确定将 XML 文本传递给 LoadXml 方法吗?看起来你正在传递一个 Url,但它不是那样工作的......

标签: c# xml xpath


【解决方案1】:

你的意思是@"/RF_SearchTermBanners/ImageName"?在 XPath 中,@ 符号代表一个属性。

【讨论】:

  • 嗯,我是 Xml 解析的新手,我是从谷歌搜索得到的。所以我把之前的 XPath 改成了“RF_SearchTermBanners/ImageName”,还是报同样的错误。
  • 这将在元素 RF_SearchTermBanners 中查找名为 RF_SearchTermBanners 的元素。将 XPath 更改为 ImageName 或 /RF_SearchTermBanners/ImageName(以 / 开头)。
  • 解决了这个问题。我对此很幼稚,这很简单。谢谢。
猜你喜欢
  • 2012-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2014-05-10
相关资源
最近更新 更多