[英]Get value of an Xml attribute using Linq to Xml
我有這樣的XML:
<?xml version="1.0" encoding="utf-8"?>
<Projects>
<Project>
<Name>Projekt0</Name>
<Information>
<Version>1.0</Version>
<Info>test-project</Info>
<CreateDate>25.02.2015</CreateDate>
</Information>
<Files ID="1" path="D:\Data\ID1">
<file>one_file</file>
<file>another_file</file>
</Files>
<Files ID="2" path="D:\Data\ID2">
<file>someFile.txt</file>
</Files>
</Project>
</Projects>
它包含更多的“項目”節點,但這不是必需的。
首先,我通過名稱選擇一個特定的項目。 這已經有效,並且可以通過以下方式完成:
var entries = from items in xelement.Elements("Project")
where (string)items.Element("Name").Value == projectName
select items;
條目現在包含所需項目的所有內容。
我的一種方法需要知道兩個“文件”節點的路徑值。 我已經嘗試過一些東西,但是還不能正常工作。
我的第一個嘗試是創建一個新的'var',例如'entries',將其轉換為數組,然后選擇索引以將值保存為字符串。
var path1 = from item in entries.Elements("Files")
where (string)item.Attribute("ID").Value == "1"
select item.Attribute("path").Value;
string path01 = path1.toArray()[0];
那是行不通的,我不確定為什么。 抱歉,這是一個初學者的問題,但是我對xml&linq的處理還不夠。
編輯:
較低的“ entries”變量是第一個linq代碼的輸出。 因此,“條目”包含整個項目。 當前,path1不包含任何元素。
entries
是項目節點的序列。 在搜索ID屬性之前,先獲取“文件”子節點
var path1 = from item in entries.Elements("Files")
where (string)item.Attribute("ID").Value == "1"
select item.Attribute("path").Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.