简体   繁体   English

使用LINQ to XML和未知元素获取属性值

[英]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. 作为项目的一部分,我需要查询XML文件并根据搜索条件查找数据。 I have tried some examples using XDocument but my issue is there are about 7 variations on the XML file needing parsed. 我已经尝试过使用XDocument一些示例,但是我的问题是需要解析的XML文件大约有7种版本。 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? 如果我想要收集错误的搜索名称,是否可以仅使用文件中找到的属性名称使用LINQ进行搜索?

Assuming you want to find all nodes in the document which contain an ErrorCode attribute: 假设您要查找文档中包含ErrorCode属性的所有节点:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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