从XElement中读取特定元素
本文关键字:元素 读取 XElement | 更新日期: 2023-09-27 18:10:44
我想使用c#将sharepoint列表的选择列中的multiecheckbox项绑定到asp.net checkboxlisttitem。我正在使用XELEMENT检索List的信息:
XElement listStructure;
listStructure = proxy.GetList("WebsiteSubscriber");
<Field Type="MultiChoice" DisplayName="Area" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" FillInChoice="FALSE" ID="{16cc1615-a490-44de-a870-c7ebe603e2cc}" SourceID="{2c8a80ea-38c5-48f7-9d7d-400d445a5e64}" StaticName="Area" Name="Area" ColName="ntext2" RowOrdinal="0">
<Default>Articles</Default>
<CHOICES>
<CHOICE>Articles</CHOICE>
<CHOICE>Websites</CHOICE>
<CHOICE>Books</CHOICE>
</CHOICES>
</Field>
我想从这个XML中读取选择。并且只获取"文章,网站,书籍"的值
注意:这个XML可能包含许多章节与<choices>
我想通过<fieldType>
或DisplayName="Area"属性来获取它,并在c#中获得值。
var xml = @"<Field Type=""MultiChoice"" DisplayName=""Area"" Required=""FALSE"" EnforceUniqueValues=""FALSE"" Indexed=""FALSE"" FillInChoice=""FALSE"" ID=""{16cc1615-a490-44de-a870-c7ebe603e2cc}"" SourceID=""{2c8a80ea-38c5-48f7-9d7d-400d445a5e64}"" StaticName=""Area"" Name=""Area"" ColName=""ntext2"" RowOrdinal=""0"">
<Default>Articles</Default>
<CHOICES>
<CHOICE>Articles</CHOICE>
<CHOICE>Websites</CHOICE>
<CHOICE>Books</CHOICE>
</CHOICES>
</Field>";
var doc = XDocument.Parse(xml);
XElement element =
doc.Descendants("Field")
.First(field => (string)field.Attribute("DisplayName") == "Area");
string[] result =
element.Descendants("CHOICE")
.Select(v => (string)v)
.ToArray();
Console.WriteLine(string.Join(Environment.NewLine, result));
打印:
Articles
Websites
Books
试试这个:
var temp =
listStructure.Descendants("Field")
.Where(i => i.Attribute("DisplayName").Value == "Area")
.Select(i => i.Descendants("CHOICE")
.Select(j => j.Value)).ToList();
List<string> result = new List<string>();
foreach (IEnumerable<string> item in temp)
{
result.AddRange(item);
}
//result: Articles; Websites; Books