[英]How can I get the first element after an element with LINQ-to-XML?
使用此代碼,我可以從以下XML文件中獲取標題:
var xml = XElement.Load (@"C:\\test\\smartForm-customersMain.xml");
string title = xml.Element("title").Value;
但是我如何使它更精確,例如“獲取smartForm元素之后的第一個元素 ,例如:
//PSEUDO-CODE:
string title = xml.Element("smartForm").FirstChild("title");
XML:
<?xml version="1.0" encoding="utf-8" ?>
<smartForm idCode="customersMain">
<title>Customers Main222</title>
<description>Generic customer form.</description>
<area idCode="generalData" title="General Data">
<column>
<group>
<field idCode="anrede">
<label>Anrede</label>
</field>
<field idCode="firstName">
<label>First Name</label>
</field>
<field idCode="lastName">
<label>Last Name</label>
</field>
</group>
</column>
</area>
<area idCode="address" title="Address">
<column>
<group>
<field idCode="street">
<label>Street</label>
</field>
<field idCode="location">
<label>Location</label>
</field>
<field idCode="zipCode">
<label>Zip Code</label>
</field>
</group>
</column>
</area>
</smartForm>
如果你不知道smartForm
是否是根元素但是仍然想要第一個這樣的條目的標題文本,你可以使用:稍微添加安德魯的答案:
xml.DescendantsAndSelf("smartForm").Descendants("title").First().Value;
這要求有一個smartForm元素,其中包含title元素。
如果你想確保title元素是smartForm
的直接子元素,你可以使用:
xml.DescendantsAndSelf("smartForm").Elements("title").First().Value;
如果您不關心title
的名稱是什么,只是想要第一個子元素,那么您將使用:
xml.DescendantsAndSelf("smartForm").Elements().First().Value;
您想使用Descendants
軸方法,然后調用FirstOrDefault
擴展方法來獲取第一個元素。
這是一個簡單的例子:
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
String xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<smartForm idCode=""customersMain"">
<title>Customers Main222</title>
<description>Generic customer form.</description>
<area idCode=""generalData"" title=""General Data"">
<column>
<group>
<field idCode=""anrede"">
<label>Anrede</label>
</field>
<field idCode=""firstName"">
<label>First Name</label>
</field>
<field idCode=""lastName"">
<label>Last Name</label>
</field>
</group>
</column>
</area>
<area idCode=""address"" title=""Address"">
<column>
<group>
<field idCode=""street"">
<label>Street</label>
</field>
<field idCode=""location"">
<label>Location</label>
</field>
<field idCode=""zipCode"">
<label>Zip Code</label>
</field>
</group>
</column>
</area>
</smartForm>";
XElement element = XElement.Parse(xml)
.Descendants()
.FirstOrDefault();
}
}
我的任務是找到指定名稱的第一個孩子。 如果xml使用名稱空間,而不是使用
e.Elements(name).FirstOrDefault()
寫
e.Elements().FirstOrDefault(i => i.Name.LocalName == name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.