2013-08-29 187 views
0
<test-case name="SuccessfulOneTimePayment" executed="True" result="Success" success="True" time="211.262" asserts="9"> 
    <categories> 
    <category name="Regression" /> 
    </categories> 
    <properties> 
    <property name="TestcaseId" value="70592" /> 
    </properties> 
</test-case> 

任何人都可以幫助我從這個XML獲取TestcaseId值= 70592?如何使用LINQ獲取xml中的元素/元素下的屬性值

var testcaseid = xml.Root.Descendants("test-case").Elements("categories").Elements("properties") 

.Where(s => s.Attribute("name") != null) 
.ToList(); 

我試過上面的代碼,這不是幫助我。

+0

您的查詢表明,性質是類別的孩子,而事實並非如此。嘗試'xml.Root.Descendants(「test-case」)。元素(「屬性」)'。 – shahkalpesh

+0

XPath不會爲此服務嗎?爲什麼選擇LINQ? – shahkalpesh

+0

@Shahkalpesh查看下面的Cuong Le的答案,您會發現Linq在Databse到XML的許多來源中有多直觀和美妙。誰真的想學習另一種語言來使用XML? – Alireza

回答

0

要獲得屬性的值,你可以使用以下命令:

var foo = (from n in xml.Descendants("property") 
      where n.Attribute("name").Value == "TestcaseId" 
      select n.Attribute("value").Value).FirstOrDefault(); 

給出:70592

+0

認真?? 'xml.Descendants()。元素( 「屬性」)'? – MarcinJuraszek

+0

放鬆嗎?查詢很好。我已經爲你清理它 – DGibbs

+0

它返回正確結果的事實並不意味着它很好。 '後代()。元素(「屬性」)'效率很低... – MarcinJuraszek

1
XDocument.Load(xml) 
    .Descendants("property") 
    .Where(e => (string)e.Attribute("name") == "TestcaseId") 
    .Select(e => (string)e.Attribute("value")) 
    .FirstOrDefault(); 
+0

如果有額外的後代名稱爲「property」和a值? –

+0

@ It'sNotALie:請您詳細說明您的問題 –

0
XDocument newTrial = XDocument.Load(@"xxxxxxxxxxx\trial.xml"); 

    var value = from name in newTrial.Descendants("properties") 
        where name.Element("property").Attribute("name").Value != null && name.Element("property").Attribute("name").Value == "TestcaseId" 
        select name.Element("property").Attribute("value").Value; 
0
yourXDocument 
    .Root 
    .Element("properties") 
    .SelectMany(x => x.Elements("property")) 
    .Where(e => (string)e.Attribute("name") == "TestcaseId") 
    .Select(e => (string)e.Attribute("value")) 
    .FirstOrDefault(s => !string.IsNullOrEmpty(s)); 
0

我認爲你需要得到的屬性列表「值「在元素」屬性「中,其他屬性」名稱「應該注意爲空

你可以試試下面的代碼:

var testcaseid1 = xdoc.Root.Descendants("property").Where(s => s.Attribute("name") != null).Select(s => s.Attribute("value").Value).ToList(); 

或者你也可以選擇使用下面的代碼中第一次出現的值:

string testcaseid = xdoc.Root.Descendants("property").Where(s => s.Attribute("name") != null).Select(s => s.Attribute("value").Value).First(); 
相關問題