使用参数筛选属性(XPath-LINQ to XML)
本文关键字:XPath-LINQ to XML 属性 参数 筛选 | 更新日期: 2023-09-27 17:57:21
-
此代码不起作用
public HttpResponseMessage Get(string par) { String JsonData, JsonFromXML; XElement root = XElement.Load("http://www.mywebsite.com/mapdata_xml.xml"); IEnumerable<XElement> address = from el in root.Elements("marker") where (string) el.Attribute("province") == par orderby (string)el.Attribute("name") select el; var XMLData = ""; foreach (XElement el in address) XMLData = XMLData + el; //XMLData = "<markers>" + XMLData + "</markers>"; XmlDocument xd = new XmlDocument(); xd.LoadXml("<markers>" + XMLData + "</markers>"); JsonFromXML = JsonConvert.SerializeXmlNode(xd); JsonFromXML = JsonFromXML.Remove(0, 11); JsonFromXML = JsonFromXML.Substring(0, JsonFromXML.Length - 1); JsonData = JsonFromXML.Replace("'"@", "'""); return new HttpResponseMessage() { Content = new StringContent(JsonData) }; }
网页接口 : http://localhost:55607/api/Test?par=%22Pursat%22
参数:标准
问:我有一个 Web API (http://localhost:55607/api/Test?par=%22Pursat%22)。我想将参数"Pursat"传递给 ASP.Net(公共HttpResponseMessage Get(字符串par)名称"Par")。然后我一无所获。但是,当我像这样使用时(其中(字符串)el。属性("省") == "Pursat"),我可以从我的代码中获取数据。
-
这段代码效果很好
public HttpResponseMessage Get(string par) { String JsonData, JsonFromXML; XElement root = XElement.Load("http://www.mywebsite.com/mapdata_xml.xml"); IEnumerable<XElement> address = from el in root.Elements("marker") where (string) el.Attribute("province") == "Pursat" orderby (string)el.Attribute("name") select el; var XMLData = ""; foreach (XElement el in address) XMLData = XMLData + el; //XMLData = "<markers>" + XMLData + "</markers>"; XmlDocument xd = new XmlDocument(); xd.LoadXml("<markers>" + XMLData + "</markers>"); JsonFromXML = JsonConvert.SerializeXmlNode(xd); JsonFromXML = JsonFromXML.Remove(0, 11); JsonFromXML = JsonFromXML.Substring(0, JsonFromXML.Length - 1); JsonData = JsonFromXML.Replace("'"@", "'""); return new HttpResponseMessage() { Content = new StringContent(JsonData) }; }
我想使用参数"par"而不是固定数据"Pursat"来查询数据。
你知道怎么解决这个问题吗?
看起来您正在用双引号传递值(HTML 编码中的 %22 = ")。 所以实际上,正在发生的事情是查询中的位置如下所示:
where (string) el.Attribute("province") == ""Pursat""
而如果你这样称呼它:
http://localhost:55607/api/Test?par=Pursat
您的 where 子句如下所示:
where (string) el.Attribute("province") == "Pursat"