如何获得XElement的价值

时间:2014-12-09 21:05:11

标签: c#

我正在解析xml文档,我需要获取Property元素的值。截至目前,我有一行代码返回:

<Property name="ID" value="thevalueineed"/>

这是我使用的代码行。

var ID = from el in linkedinfo.DescendantsAndSelf("Property") 
         where (string)el.Attribute("name") == "ID" 
         select el.Attributes("value").ToString();

我错过的下一步是什么?我会从thevalueineed中的那个元素中获得var ID

5 个答案:

答案 0 :(得分:5)

只需将select更改为

即可
select (string)el.Attribute("value")

工作代码。

var xDoc = XDocument.Parse(@"<root><Property name=""ID"" value=""thevalueineed""/></root>");

var ID = from el in xDoc.Root.DescendantsAndSelf("Property")
            where (string)el.Attribute("name") == "ID"
            select (string)el.Attribute("value");

var val = ID.First();

答案 1 :(得分:0)

这应该有效

var ID = from el in linkedinfo.Descendants("Property") 
         where el.Attribute("name").Value == "ID" 
         select el.Attribute("value").Value;

答案 2 :(得分:0)

我个人会使用.Value而不是强制转换为字符串:

XElement linkedTeethInfo = XElement.Parse(@"<Property name=""ID"" value=""thevalueineed""/>");

var ID = from el in linkedTeethInfo.DescendantsAndSelf("Property") 
    where el.Attribute("name").Value == "ID" 
    select el.Attribute("value").Value;

Console.WriteLine("ID: {0}", ID.First());

在这里创建了一个小小提琴:https://dotnetfiddle.net/mrSITM

答案 3 :(得分:0)

我个人喜欢读取XML文件时使用此方法,但我不知道它是否适用于您的XML文件。

// Create a DataSet
DataSet ds = new DataSet();

// Get the data from the XML file
ds.ReadXml("C:\\myXMLFile.xml");

// Get values
foreach (DataRow dr in ds.Tables[0].Rows)
{
    string value = dr["ID"].ToString(); 
}

答案 4 :(得分:0)

select el.Attributes("value")

将返回一个类型

System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Xml.Linq.XElement,System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>>

试试这个:

var ID = element.DescendantsAndSelf("Property").Where(x => x.Attribute("name").Value == "id").Select(x => x.Attribute("value")).First();