检查xml文件中是否存在元素

时间:2013-12-17 16:37:40

标签: 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>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>

然后我有C#代码来解析它。

 XDocument doc = XDocument.Load(fileName);
 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)
  {
         y = where x.Name.LocalName == "DISPOSITION"
         select x).First().Value.ToLower() == "active" ? true : false;

事情有时没有“DISPOSITION”元素,在这种情况下,我想要

y = true; // if no "DISPOSITION" element found in file

否则,如果存在“DISPOSITION”,请保留原始代码。

如何检查?

2 个答案:

答案 0 :(得分:1)

这应该做的工作。

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);
}

答案 1 :(得分:0)

这对我有用:

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");
    }
}