簡體   English   中英

使用LINQ to XML和未知元素獲取屬性值

[英]Get Attribute Values using LINQ to XML with Unknown Elements

作為項目的一部分,我需要查詢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進行搜索?

假設您要查找文檔中包含ErrorCode屬性的所有節點:

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

您應該能夠執行這樣的操作。

        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