简体   繁体   中英

Check if xml node has attribute

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM