我有十几个解决方案,但似乎没有一个适合我想做的事情。 XML文件包含每次发布时可能不在文件中的元素。
诀窍是,查询依赖于问题值来获取答案值。这是代码:
string otherphone = (
from e in contact.Descendants("DataElement")
where e.Element("QuestionName").Value == "other_phone"
select (string)e.Element("Answer").Value
).FirstOrDefault();
otherphone = (!String.IsNullOrEmpty(otherphone)) ? otherphone.Replace("'", "''") : null;
在"联系人"集合,这里有许多名为" DataElement"的元素,每个元素都有自己的" QuestionName"和"答案"元素,所以我查询找到元素的QuestionName值是" other_phone",然后我得到答案值。当然,我需要为我正在寻找的每一个值做这个。
如何对此进行编码以忽略包含QuestionName的DataElement,其值为" other_phone"如果它不存在?
答案 0 :(得分:0)
您可以使用Any
方法检查元素是否存在:
if(contact.Descendants("DataElement")
.Any(e => (string)e.Element("QuestionName") == "other_phone"))
{
var otherPhone = (string)contact
.Descendants("DataElement")
.First(e => (string)e.Element("QuestionName") == "other_phone")
.Element("Answer");
}
此外,如果您使用显式强制转换,请不要使用Value
属性。显式强制转换的要点是,如果元素不是,则避免可能的异常找不到。如果在演员表之前使用了两者,访问Value
属性将抛出异常。
或者,您也可以在没有FirstOrDefault
的情况下使用Any
方法,并执行空检查:
var element = contact
.Descendants("DataElement")
.FirstOrDefault(e => (string)e.Element("QuestionName") == "other_phone");
if(element != null)
{
var otherPhone = (string)element.Element("Answer");
}
答案 1 :(得分:0)
所以你想知道other_phone
是否存在?
XElement otherPhone = contact.Descendants("QuestionName")
.FirstOrDefault(qn => ((string)qn) == "other_phone");
if (otherPhone == null)
{
// No question with "other_phone"
}
else
{
string answer = (string)otherPhone.Parent.Element("Answer");
}