2009-08-29 93 views
1

屬性我有一些這樣的XML:充分利用XML

<Action id="SignIn" description="nothing to say here" title=hello" /> 

使用LINQ to XML,我怎麼能得到ID的內在價值?我不是我的dev的機器(anothe機無開發的東西,但這樣的憑證),但我還沒有嘗試過:

var x = from a in xe.Elements("Action") 
    select a.Attribute("id").Value 

我可以做類似的規定?我不想要一個布爾條件。另外,在引入LINQ之前,如何使用傳統的XML方法完成這項工作(儘管我在.NET 3.5上)。

感謝

回答

3

你可以做類似

XDocument doc = XDocument.Parse("<Action id=\"SignIn\" description=\"nothing to say here\" title=\"hello\" />"); 
var x = from a in doc.Elements("Action") 
     select a.Attribute("id").Value; 

string idValue = x.Single(); //Single() is called for this particular input assuming you IEnumerable has just one entry 

隨着XmlDocument的,你可以做

XmlDocument doc = new XmlDocument(); 
doc.LoadXml("<Action id=\"SignIn\" description=\"nothing to say here\" title=\"hello\" />"); 
var x = doc.SelectSingleNode("Action/@id"); 
string idValue = x.Value; 

HTH

+0

雖然我標誌着這個作爲答案,這是行不通的。我的XML線是這樣的: <?XML版本= 「1.0」 編碼= 「UTF-8」> Feed訂閱 <輪廓標題=」 Omea新聞「text =」Omea新聞「description =」JetBrains Omea產品系列的最新消息「xmlUrl =」http://jetbrains.com/omearss.xml「htmlUrl =」http://www.jetbrains.com/omea「 type =「rss」/> 也許我應該使用xpath? – dotnetdev 2009-08-29 17:00:58

+0

SelectSingleNode的參數_is_是一個XPath查詢。 你能解釋更多「它不工作」嗎?有什麼問題? 您複製的xml片段無效:它沒有正確關閉,屬性之間有分號。 你想從中提取什麼? – 2009-08-29 17:20:54

2

這裏是一個小例子,顯示瞭如何做到這一點:

using System; 
using System.Xml.Linq; 

class Program 
{ 
    static void Main() 
    { 
     String xml = @"<Action 
       id=""SignIn"" 
       description=""nothing to say here"" 
       title=""hello""/>"; 

     String id = XElement.Parse(xml) 
      .Attribute("id").Value; 
    } 
} 
1

使用 「傳統」 的XML方法,你會做一些這樣的:

XmlDocument doc = new XmlDocument(); 
doc.Load("XML string here"); 

XmlNode node = doc.SelectSingleNode("Action"); 
string id = node.Attributes["id"].Value 

安德魯有正確的方式來使用Linq來做到這一點。

0

使用傳統的XML文檔,假設您已經有了您想要的動作節點,使用SelectSingleNode或遍歷文檔,您可以獲取id屬性的值。

ActionNode.Attributes("id").Value 
0

你幾乎擁有了它,只要 'XE' 是XElement包含您要查找的那個「動作」元素是第一個/唯一的「行動」,在的XElement元素:

string x = xe.Element("Action").Attribute("id").Value;