简体   繁体   English

如何获得XElement的价值

[英]How to get the Value of XElement

I am parsing through an xml doc and I need to get the value of a Property element. 我正在通过xml文档进行解析,我需要获取Property元素的值。 As of right now I have a line of code that returns this: 截至目前,我有一行代码返回以下内容:

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

Here is my line of code used. 这是我使用的代码行。

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

What would be the next step I am missing that would I get thevalueineed from that Element that I have in var ID ? 这将是下一步我很想念,将我得到thevalueineed从元素,我在var ID

Just change your select as 只需将您的select更改为

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

A working code. 工作代码。

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();

This should work 这应该工作

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

I would personally use .Value instead of casting to string: 我个人将使用.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());

Created a small fiddle here: https://dotnetfiddle.net/mrSITM 在这里创建了一个小提琴: https : //dotnetfiddle.net/mrSITM

I personally like this method when reading XML files but I don't know if it will work with your XML file. 在读取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(); 
}
select el.Attributes("value")

will return an a type 将返回一个类型

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

try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM