C# 检查xml文件中是否存在元素
我有一个xml文件C# 检查xml文件中是否存在元素,c#,xml,C#,Xml,我有一个xml文件 <?xml version="1.0"?> <RCATS xsi:noNamespaceSchemaLocation="/opt/radical/xml/schemas/RcatsExternalInterface.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <IDENTIFICATION-RECORD ACTION="ADD"> <ID>
<?xml version="1.0"?>
<RCATS xsi:noNamespaceSchemaLocation="/opt/radical/xml/schemas/RcatsExternalInterface.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<IDENTIFICATION-RECORD ACTION="ADD">
<ID>1200020100</ID>
<TRANSACTION-ID>3r7we43556564c6r34vl6z)zM6KF8i</TRANSACTION-ID>
<LAST-NAME>GEORGE</LAST-NAME>
<FIRST-NAME>BUSH</FIRST-NAME>
<MIDDLE-NAME>W</MIDDLE-NAME>
</IDENTIFICATION-RECORD>
</RCATS>
问题是有时候没有“处置”元素,在这种情况下,我想要
y = true; // if no "DISPOSITION" element found in file
否则,如果有“DISPOSITION”,则保留原始代码
如何检查它?这就可以了
XDocument doc = XDocument.Load("test.xml");
var a = from x in doc.Descendants()
select x;
var d = from x in a
where x.Name.LocalName == "IDENTIFICATION-RECORD"
select x;
foreach (var i in d)
{
var disp = i.Element("DISPOSITION");
var y = disp == null ? true : (disp.Value.ToLower() == "active" ? true : false);
}
这对我很有用:
foreach (XElement element in doc.Descendants().
Where(x=>x.Name.LocalName=="RCATS").
Descendants().
Where(y=>y.Name.LocalName=="IDENTIFICATION-RECORD"))
{
foreach (XElement node in element.Descendants())
{
if (node.Name.LocalName == "DISPOSITION")
if (node.Value == "ACTIVE")
Console.Write("Disposition exists and is true");
}
}
System.InvalidOperationException:序列在哪一行不包含元素?我编辑了我的答案,它在这两种情况下对我都有效——disposition元素缺失,并且存在于xml.var disp=I.element(“disposition”);在这一行。
foreach (XElement element in doc.Descendants().
Where(x=>x.Name.LocalName=="RCATS").
Descendants().
Where(y=>y.Name.LocalName=="IDENTIFICATION-RECORD"))
{
foreach (XElement node in element.Descendants())
{
if (node.Name.LocalName == "DISPOSITION")
if (node.Value == "ACTIVE")
Console.Write("Disposition exists and is true");
}
}