0

我正在使用以下 linq to xml 查询在 XML 文件中搜索元素

XElement inspections = XElement.Load(new StreamReader( Server.MapPath(ResolveUrl(SelectInspection.InspectionFilePath)),Encoding.UTF8));

XElement inspection = (from elements in inspections.Elements("inspection")
                                       where elements.Element("inspectionid").Value == inspectionId.ToString()
                                       && elements.Element("databasename").Value == Encoding.UTF8.GetString(Request.ContentEncoding.GetBytes (Request.QueryString("DbName")))
                                       select elements).Single();

我的 xml 文件是

<?xml version="1.0" encoding="utf-8"?>
<inspections>
   <inspection>
    <inspectionid>8</inspectionid>
    <databasename>Åker</databasename>
    <exported>false</exported>
  </inspection>
 </inspections>

尽管Request.QueryString("DbName")等于 "Åker",但查询不返回任何结果。

4

2 回答 2

2

这在我看来是错误的:

Encoding.UTF8.GetString(Request.ContentEncoding
                               .GetBytes(Request.QueryString("DbName")))

为什么Request.QueryStringASP.NET 尚未应用适当的解码?

我建议你把问题分成两半:

  • 确保 LINQ to XML 可以找到字符串:在带有硬编码数据的控制台应用程序中执行此操作
  • 确保您可以获得正确的查询字符串:通过将 Unicode 代码点记录Request.QueryString("DbName")为整数来做到这一点

希望您能够Request.QueryString("DbName")直接使用。

于 2011-01-14T09:55:20.027 回答
0

我创建了一个包含以下内容的测试网页:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
     <a href="WebForm1.aspx?DbName=Åker">Test</a><br />
    <asp:Label runat="server" ID="lblTest"></asp:Label>
    </form>
</body>
</html>

它的代码隐藏:

using System;
using System.Linq;
using System.Xml.Linq;

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?><inspections>   <inspection>    <inspectionid>8</inspectionid>    <databasename>Åker</databasename>    <exported>false</exported>  </inspection> </inspections>";
        var inspections = XElement.Parse(xmlStr);
        XElement inspection = (from elements in inspections.Elements("inspection")
                               where elements.Element("databasename").Value == Request.QueryString["DbName"]
                               select elements).FirstOrDefault();
        lblTest.Text = (inspection != null).ToString();

    }
}

当我单击Test链接时, lblTest 文本变为 True - 因此,查询按预期找到了元素。

除了可能解决问题的 Jon Skeet 的解决方案之外,您可能会传递错误的inspectionId参数值导致搜索失败。

于 2011-01-14T10:14:56.757 回答