简体   繁体   中英

Get Attribute Values using LINQ to XML with Unknown Elements

As part of a project I am working on I need to query XML files and find data based on search criteria. I have tried some examples using XDocument but my issue is there are about 7 variations on the XML file needing parsed. So I don't know the element names, just what attributes the file might contain. for each variation I have concatenated the files into one file, it was my theory it would make searching easier. That theory so far has been proven wrong.

All will have some or all of a list of Attributes. for example

<root>
    <T1>
        <T11 name="123"/>
        <H05 FileType="T52" ClientID="POB" />
    </T1>
    <T1>
        <T11 name="1234"/>
        <H05 FileType="T2" ClientID="POB" />
        <E1 ErrorCode="AA00" ErrorText="There was an Error" />
        <E1 ErrorCode="BB00" ErrorText="There was another Error" />
    </T1>
</root>

If I wanted a collection of errors searching name, is it possible to search with LINQ using only attribute names found in the file?

Assuming you want to find all nodes in the document which contain an ErrorCode attribute:

XDocument document = LoadXml();
IEnumerable<XElement> errorNodes = document
   // Find all descendant nodes:
   .Descendants() 
    // With an "ErrorCode" attribute:
   .Where(el => el.Attribute("ErrorCode") != null);

You should be able to do something like this.

        var xmlString = @"<root>
        <T1>
        <T11 name=""123\""/>
        <H05 FileType=""T52"" ClientID=""POB"" />
        </T1>
        <T1>
        <T11 name=""1234""/>
        <H05 FileType=""T2"" ClientID=""POB"" />
        <E1 ErrorCode=""AA00"" ErrorText=""There was an Error"" />
        <E1 ErrorCode=""BB00"" ErrorText=""There was another Error"" />
        </T1>
        </root>";

        var xml = XDocument.Parse(xmlString);

        var names = from x in xml.Descendants().Attributes("name") select x.Parent;

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