我的xml中有以下内容:
<mur>
<bak>
</bak>
<itemfb ident="c_fb">
<flow_m>
<mat>
<text texttype="text/plain">correct answer comments</text>
</mat>
</flow_m>
</itemfb>
<itemfb ident="gc_fb">
<flow_m>
<mat>
<text texttype="text/plain">wrong, you made a blunder</text>
</mat>
</flow_m>
</itemfb>
</mur>
现在,'itemfb'标签可能存在也可能不存在于'mur'标签内,如果存在,我需要解析并获取值“正确答案评论”(或)“错误,你犯了一个大错”取决于“itemfb”ident。这是我尝试过的。假设rowObj从“mur”加载了xml,而'ns'是命名空间
if (rowObj.Elements(ns + "itemfb").Any())
{
var correctfb = (from cfb in rowObj
.Descendants(ns + "itemfb")
where (string)cfb.Attribute(ns + "ident").Value == "cfb"
select new
{
ilcfb = (string)cfb.Element(ns + "mat")
}).Single();
some_variable_1 = correctfb.ilcfb;
var incorrectfb = (from icfb in rowObj
.Descendants(ns + "itemfb")
where (string)icfb.Attribute(ns + "ident").Value == "gcfb"
select new
{
ilicfb = (string)icfb.Element(ns + "mat")
}).Single();
some_variable_2 = incorrectfb.ilicfb;
}
答案 0 :(得分:0)
这应该是获取所需信息的一种方式。为简单起见,我省略了ns。
var correctfb = rowObj.Descendants("mur")
.Descendants("itemfb")
.Where(e => e.Attribute("ident").Value == "c_fb")
.Descendants("text").FirstOrDefault();
if (correctfb != null)
some_variable_1 = correctfb.Value;
var incorrectfb = rowObj.Descendants("mur")
.Descendants("itemfb")
.Where(e => e.Attribute("ident").Value == "gc_fb")
.Descendants("text").FirstOrDefault();
if (incorrectfb != null)
some_variable_2 = incorrectfb.Value;