簡體   English   中英

分別獲取XML中的標簽值

[英]Getting tag values in XML separately

這是我的XML文件:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<categories>
    <category1 name="Music">
        <file>tabla.txt</file>
        <file>sitar.txt</file>
    </category1>

    <category2 name="Documents">
        <file>OCD1.txt</file>
        <file>OCD2.txt</file>
    </category2>

    <category3 name="Movies">
            <file>Thisistheend.txt</file>
        <file>TheInternship.txt</file>
    </category3>
</categories>

我正在使用以下查詢來獲取標簽值:

q = from x in doc.Descendants() where (x.Attributes().Count()>0
&& (x.Attribute("name").Value == key) select x; 

但是<File>標記值已附加。 當我嘗試顯示每個的值時,例如:“文檔”的<file>標記值在ListView框中顯示為“ OCD1.txtOcd2.txt”。 如何在LINQ查詢中將這兩個值分開?

您可以使用SelectMany查詢來獲取文件內容。 在查詢語法中,您可以通過在匹配類別上添加額外的from / select查詢來完成此操作。

var query = from x in doc.Descendants()
            where (string)x.Attribute("name") == key
            from file in x.Elements("file")
            select file.Value;

還要注意,我更新了過濾條件以直接檢查name屬性。 您可以避免檢查屬性計數。 這是不必要的,並且不能保證name屬性的存在。 如果要防止缺少name屬性,則可以強制轉換屬性,如果不存在該屬性將返回null 我使用以下代碼完成了此操作: (string)x.Attribute("name") == key

使用Lambda表達式方法處理LINQ查詢,也可以滿足您的需求。

var q = doc.Descendants()
           .Where(x => (string)x.Attribute("name") == key)
           .SelectMany(x => x.Elements("file"))
           .Select(x => x.Value);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM