2009-08-29 99 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;