0

I have an XML file which is generated from a windows application like below "Repport.xml":

<ArrayOfAutoReportXML>  
    <AutoReportXML ReportName="Report1" ReportID="1" />
    <AutoReportXML ReportName="Report2" ReportID="2" />
    <AutoReportXML ReportName="Report3" ReportID="3" />
    <AutoReportXML ReportName="Report4" ReportID="4" />
    <AutoReportXML ReportName="Report5" ReportID="5" />
</ArrayOfAutoReportXML>

I am trying to check if ReportName already exists and i am trying below code to do that:

using (FileStream fs = new FileStream("Repport.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
    XDocument doc = XDocument.Load(fs);

    string attrReportname = (string) doc.Elements("AutoReportXML")
        .Where(ox => ox.Attribute("ReportName").Value.ToString() == ReportName)
        .FirstOrDefault();
}

And attrReportName is null.

1 Answer 1

1

The issue is that Elements will only find the immediate child Elements from the current context. The only element returned by doc.Elements() would be ArrayOfAutoReportXML.

What you need is Descendants, which traverse all elements in the document.

To check if a report exists based on that attribute:

var reportExists = doc
    .Descendants("AutoReportXML")
    .Attributes("ReportName")
    .Any(x => x.Value == "Report1");

If you needed to check using more than one attribute:

var reportExists = doc
    .Descendants("AutoReportXML")
    .Any(x => (string)x.Attribute("ReportName") == "Report1" && 
              (int)x.Attribute("ReportID") == 1);

See this fiddle for a working demo.

Sign up to request clarification or add additional context in comments.

3 Comments

how to check reportname and reportid more than one attribute.
@Tan I've added a second example
thank you sir, it has become big headache for me for 20 minutes..thank you

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.