0

I have a xml file.

<?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>

Then I have C# code to parse it.

 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;

The thing is sometimes there is no "DISPOSITION" element, in this case, I want

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

Otherwise, keep the original code there if "DISPOSITION" is there.

How to check it?

2 Answers 2

1

This should do the work.

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

System.InvalidOperationException: Sequence contains no elements
On which line? I edited my answer, it works for me in both cases - disposition element missing and present in xml.
var disp = i.Element("DISPOSITION");in this line.
0

This worked for me:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.