使用LINQ to XML with Unknown Elements获取属性值

时间:2013-04-05 14:54:49

标签: c# xml linq

作为我正在研究的项目的一部分,我需要查询XML文件并根据搜索条件查找数据。我使用XDocument尝试了一些示例,但我的问题是需要解析的XML文件有大约7种变体。所以我不知道元素名称,只知道文件可能包含的属性。对于每个变体,我将文件连接成一个文件,这是我的理论,它将使搜索更容易。到目前为止,这一理论被证明是错误的。

所有将具有部分或全部属性列表。例如

<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>

如果我想搜索名称的错误集合,是否可以仅使用文件中找到的属性名称来搜索LINQ?

2 个答案:

答案 0 :(得分:1)

假设您要查找文档中包含ErrorCode属性的所有节点:

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

答案 1 :(得分:0)

你应该可以做这样的事情。

        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;