[英]How to get the Attribute name and the Elemnt value using XDocument
I am currently working on an ASP.NET Web Forms application and .NET 4.0. 我目前正在使用ASP.NET Web窗体应用程序和.NET 4.0。 I don't have previous experience with XML in .NET.
我以前没有在.NET中使用XML的经验。 I created this very simple XML document from which I want to extract the attributes with their respective data :
我创建了这个非常简单的XML文档,我想从中提取属性及其各自的数据:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<DataTable>
<Filter>true</Filter>
<DropDown>true</DropDown>
</DataTable>
</configuration>
And I try this code: 我尝试下面的代码:
var path = HttpContext.Current.Server.MapPath("/XML/Settings.xml");
XDocument xdoc = XDocument.Load(path);
IEnumerable<XElement> xnodes = xdoc.Root.Elements("DataTable");
List<string> list = new List<string>();
foreach (XElement xnn in xnodes)
{
list.Add(xnn.Value);
}
which results in in one element in my List
with value truetrue
. 这导致我的
List
中的一个元素的值为truetrue
。 I know here I don't try to get both the attribute name and the content inside it, but in general that's what I wanna do, so how can I accomplish it? 我知道在这里我不会尝试同时获取属性名称和内容,但是总的来说,这就是我想做的,那么我该如何完成呢?
There is no attribute here. 这里没有属性。 I think you want a dictionary where keys are the element names and values are element values
我认为您想要一个字典,其中键是元素名称,值是元素值
var dictionary = xdoc.Root.Elements("DataTable").Elements()
.ToDictionary(x => x.Name.LocalName, x => (string)x)
You can get all elements as dictionary 您可以将所有元素作为字典
var dictionary = xdoc.Descendants().
ToDictionary(x => x.Name.LocalName, x => x.Value)
had you tried using the XmlConvert.ToBoolean()
function? 您是否尝试过使用
XmlConvert.ToBoolean()
函数?
Also, I would have preferred to use Linq syntax when working with XML files. 另外,在处理XML文件时,我更喜欢使用Linq语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.