简体   繁体   中英

How to select record from XML using LINQ?

I have an XML document.

<checksum>
    <kbbest>
        <delimiter value="length" offset="0">2</delimiter>
        <record name="header">
            <identificators>
                <identificator value="char('2')" offset="0">HO</identificator>
                <identificator value="char('2')" offset="0">HE</identificator>
            </identificators>
            <fields>
                <!-- some fields -->
            </fields>
        </record>
        <record name="footer">
            <identificators>
                <identificator value="char('2')" offset="0">TO</identificator>
                <identificator value="char('2')" offset="0">TF</identificator>
            </identificators>
            <fields>
                <!-- some fields -->
            </fields>
            </record>
    </kbbest>
</checksum>

I want to select all information stored in record according to identificator. My Script:

string recordType = "HE"
IEnumerable<XElement> rec = null;
rec = from xr in doc.Element(fileType).Elements("record")
      where (string)xr.Element("identificators").Element("identificator") == recordType
      select xr;

Error: This select can find only records which has identificator HO or TO.

If I tried to write it as an list

string recordType = "HE"
IEnumerable<XElement> rec = null;
rec = from xr in doc.Element(fileType).Elements("record")
      where xr.Element("identificators").Elements("identificator").Cast<String>().Contains(recordType)
      select xr;

Error: Can't cast XElement to String

I believe this is what you want

string recordType = "HE"
IEnumerable<XElement> rec = null;
rec = from xr in doc.Element(fileType).Descendants ("record")
      where xr.Element("identificators")
              .Elements("identificator")
              .Any(x => x.Value == recordType)
      select xr;

you need to use Descendants to get at any elements that are more than one level deep. Then you have to compare the Value of the XElement to the string 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