简体   繁体   中英

linq search XML Attribute

I found a question that was very close to mine. How to search XML using LINQ-to_XML Query

using the below xml structure:

<EnfocusReport>
      <Report>
        <PreflightResult errors="2" criticalfailures="0" noncriticalfailures="0" signoffs="0" fixes="12" warnings="0">
              <PreflightResultEntry type="Check" level="error">
            <PreflightResultEntryMessage xml:lang="en-US">
              <Message>Media box width is 792 pt, should be equal to 612 pt, Media box height is 612 pt, should be equal to 792 pt (9x on pages 1-9)</Message>

    ….
    </EnfocusReport>
      </Report>

I need to find all the elements PreflightResultEntry that have attributes level="error" :

      <PreflightResultEntry type="Check" level="error">

Then be able to read the element PreflightResultEntryMessage/Message for the message:

  <Message>Media box width is 792 pt, should be equal to 612 pt, Media box height is 612 pt, should be equal to 792 pt (9x on pages 1-9)</Message>

So I modified it to what I thought was the correct structure however my return query is coming up empty(no data).

My code is:

   var result2 = from EnfocusReport in XDocument.Load(args[0]).Root.Elements("EnfocusReport")
                          from Report in EnfocusReport.Elements("Report")
                          from PreflightResultEntry in Report.Elements("PreflightResultEntry")
                          from PreflightResultEntryMessage in PreflightResultEntry.Elements("PreflightResultEntryMessage")
                          where PreflightResultEntry.Attributes("level").Equals("error")
                          select PreflightResultEntryMessage.Elements("Message");



        foreach (var el in result2)
        {
            Console.WriteLine(el);
            Console.ReadLine();

        }

Here's how I would do:

var messages = XDocument.Load(args[0])
                        .Descendants("PreflightResultEntryMessage")
                        .Where(x => x.Parent != null && 
                               x.Parent.Name == "PreflightResultEntry" &&
                               x.Parent.Attribute("level") != null &&
                               x.Parent.Attribute("level").Value == "error")
                        .Select(x => x.Element("Message").Value);

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