请检查我的代码 - XML -
<LocalXML>
<PnrDetails SearchType="Outbound">
<GDSPNR></GDSPNR>
</PnrDetails>
<PnrDetails SearchType="Inbound">
<GDSPNR></GDSPNR>
</PnrDetails>
</LocalXML>
代码 -
XDocument doc = XDocument.Load(@"RSP.xml");
var ele = doc.Root.Elements("PnrDetails");
foreach (XElement e in ele)
{
if (e.Element("GDSPNR").Value.Equals(""))
{
e.Elements().Remove();
e.Add(new XElement("ErrorMessage", "Booking is not confirmed")
);
}
}
我的代码工作正常。现在我的问题是我可以在上面的代码中使用Lambda Expression来检查GDSPNR值是否为null。如果是,那么请告诉我如何?
提前致谢。
编辑XML -
<LocalXML>
<PnrDetails SearchType="Outbound">
<GDSPNR></GDSPNR>
<SPNR>abc</SPNR>
<DSPNR>xyz</DSPNR>
</PnrDetails>
<PnrDetails SearchType="Inbound">
<GDSPNR></GDSPNR>
<SPNR>abx</SPNR>
<DSPNR>cds</DSPNR>
</PnrDetails>
</LocalXML>
答案 0 :(得分:1)
这个怎么样(完全基于你当前的逻辑做法):
IEnumerable<XElement> nodesToBeReplaced = document.Root
.Elements("PnrDetails")
.Descendants("GDSPNR")
.Where(element => element.Value.Equals(string.Empty));
foreach (XElement element in nodesToBeReplaced)
{
element.Name = "ErrorMessage";
element.Value = "Booking is not confirmed";
}
如果你的意思是,PnrDetails没有GDSPNR的子标签,就像这样:
<PnrDetails SearchType=""Outbound"">
</PnrDetails>
然后您可以执行以下操作:
IEnumerable<XElement> nodesWithMissingChildElements = document.Root
.Elements("PnrDetails")
.Where(element => !element.Descendants("GDSPNR").Any());
答案 1 :(得分:1)
我的建议:
XDocument doc = XDocument.Load(@"RSP.xml");
var ele = doc.Root.Elements("PnrDetails");
foreach (XElement e in ele.Where(e => string.IsNullOrEmpty((string)e.Element("GDSPNR"))))
{
e.Elements().Remove();
e.Add(new XElement("ErrorMessage", "Booking is not confirmed"));
}
答案 2 :(得分:0)
那么您认为XML元素节点的“空”检查是什么?您当前的代码检查Value属性是否为空字符串,如果您要做的只是将if
语句的检查移到查询表达式中,然后执行此操作。
var ele = doc.Root.Elements("PnrDetails").Where(p => p.Element("GDSPNR").Value == "");
或者您想要检查是否存在子元素GDSPNR
:
var ele = doc.Root.Elements("PnrDetails").Where(p => p.Element("GDSPNR") != null);