[英]how to read value of an xml node (single) using linq to xml
我有一個類似於下面的xml結構:
<test>
<test1>test1 value</test1>
</test>
現在我正在使用LINQ to xml代碼讀取節點的值。
var test = from t in doc.Descendants("test") select t.Element("test1").Value;
Console.WriteLine("print single node value");
foreach (var item in test)
{
Console.WriteLine(item);
}
上面的代碼工作正常,但在這里我有一個單一的節點,但要回溯價值我使用foreach循環,我不認為是好..沒有foreach循環做同樣的事情更好的方式謝謝。
嘗試這樣的事情:
using System;
using System.Linq;
using System.Xml.Linq;
public class Example
{
static void Main()
{
String xml = @"<test>
<test1>test1 value</test1>
</test>";
var test = XElement.Parse(xml)
.Descendants("test1")
.First()
.Value;
Console.WriteLine(test);
}
}
您還可以嘗試提供以下XML文件路徑:
XElement xmldoc = XElement.Load("filePath");
var nodeValueFromXMlFile = xmldoc
.Descendants("node name")
.First()
.Value;
System.Console.WriteLine(nodeValueFromXMlFile);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.