Linq对XML不区分大小写的查询 [英] Linq to XML case-insensitive query
问题描述
嗨!
我有问题。我在xml文档中搜索特定的属性值。
这是我的代码:
XElement root = XElement.Load(System.Environment.CurrentDirectory +\\Documents\\Codec \\ super.xml);
//在super.xml文件的VAR-Region中搜索信号的名称。显示PACKET类型的所有祖先元素,这是第一个属性(name)
var result =(from t in root.Descendants(VAR)where(string)t.Attribute( name)== textBox1.Text select t.Ancestors(PACKET)。Attributes()。First()。Value)。ToList();
这很好用,我得到了我想要的,但我不能执行不区分大小写的搜索!
所以我的代码的用户必须知道正确区分搜索值的区分大小写。
某些搜索值为:DcdeF1234,因此用户必须在搜索文本框中输入该值。这不是非常用户友好。如果用户可以写的话会更好:dcdef1234。
我尝试在网上找到不同的代码,但是没有成功。
例如:
其中 d.Element( name)。值。 IndexOf(
textBox1。 Text ,StringComparison.InvariantCultureIgnoreCase)> 0
- >这有效,但是如果找不到搜索值,我会得到一个null-reference-exception!
问候
Adam
由于值null
,我会这样做:
var result =( from t in root.Descendants( VAR)
let nameAttr = t。属性( name)
其中 nameAttr!= null && nameAttr.Value!= null // 缺少属性或缺少值,在两种情况下都跳过
where String .Equals(nameAttr.Value,textBox1.Text,StringComparison.OrginalIgnoreCase)
select t.Ancestors( PACKET)。Attributes()。First()。Value)
.ToList();
Hi!
I have a problem. I´m searching a xml-document for a specific attribute value.
This is my code:
XElement root = XElement.Load(System.Environment.CurrentDirectory + "\\Documents\\Codec\\super.xml"); //Search the Name of the Signal in the VAR-Region of the super.xml file. Show all ancestor elements of type PACKET and of this the first attribute ("name") var result = (from t in root.Descendants("VAR") where (string)t.Attribute("name") == textBox1.Text select t.Ancestors("PACKET").Attributes().First().Value).ToList();
This works great and I get what I want, but I can´t perform a "case-insensitive" search!
So the users of my code have to be aware of the correct case-sensitive name of the searched value.
Some searched values are: "DcdeF1234" so the user has to type exactly that value into the search-Textbox. This is not very user friendly. It would be better if the user could write : "dcdef1234".
I tried different pieces of code found on the net, but without success.
For Example:
where d.Element("name").Value.IndexOf(
textBox1.Text, StringComparison.InvariantCultureIgnoreCase) > 0
--> This works, but I get a null-reference-exception, if the search value is not found!
regards
Adam
Since value isnull
, I would do something like this:
var result = (from t in root.Descendants("VAR") let nameAttr = t.Attribute("name") where nameAttr != null && nameAttr.Value != null // Either the attribute is missing, or the value is missing, skip in both cases where String.Equals(nameAttr.Value, textBox1.Text, StringComparison.OrginalIgnoreCase) select t.Ancestors("PACKET").Attributes().First().Value) .ToList();
这篇关于Linq对XML不区分大小写的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!