从 Xnode 获取阅读器不起作用
我尝试从 XNode 获取属性,我使用以下代码
XDocument document = XDocument.Load(FilePath);
var Elements = from p in document.Descendants(modality) select p.Elements("Key_Part");
//var Attriputess = from p in document.Descendants(modality) select p.Attributes();
foreach (var Element in Elements)
{
foreach (var node in Element.Nodes())
{
XmlReader reader = node.CreateReader();
string a = reader.GetAttribute("Type");
}
}
始终等于 null 像这样的 XML 类型
<ShortcutList Version="8">
<Doctor>
<Key_Part >
<Key1 Name = "XX" Type= "XXXXXXXXX" > rrrr</Key1>
<Key2 Name = "XasfsaX" Type= "XXXXsafasfXXXXX" > rrsfsfrr</Key1>
</Key_Part>
我想获取 Key1 、 Key2 属性和值
I tried to get the attributes from XNode I use the following code
XDocument document = XDocument.Load(FilePath);
var Elements = from p in document.Descendants(modality) select p.Elements("Key_Part");
//var Attriputess = from p in document.Descendants(modality) select p.Attributes();
foreach (var Element in Elements)
{
foreach (var node in Element.Nodes())
{
XmlReader reader = node.CreateReader();
string a = reader.GetAttribute("Type");
}
}
a always equal null
the XML type like this
<ShortcutList Version="8">
<Doctor>
<Key_Part >
<Key1 Name = "XX" Type= "XXXXXXXXX" > rrrr</Key1>
<Key2 Name = "XasfsaX" Type= "XXXXsafasfXXXXX" > rrsfsfrr</Key1>
</Key_Part>
I want to get Key1 , Key2 attributes and value
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我必须说,在下面的工作查询之前,我已经修复了您提供的 XML。因此,您没有关闭最后两个标签,并且通过
标签关闭了
Key2
,这是错误的 XML。尝试以下操作,这将返回条目列表(每个键一个),其中匿名类型的每个条目都具有属性:名称、值、类型
编辑:固定 XML
I must say I've fixed XML you've provided before got working query below. So you've not closed two last tags and you've closed
Key2
by</Key1>
tag what is wrong XML.Try out following, this will return list of entries (one per key) where each entry of anonymous type with properties: Name, Value, Type
EDIT: Fixed XML
您需要确保读者位于元素上,然后才能开始获取属性。但是,除非您有充分的理由这样做,否则根本不需要
XmlReader
来获取属性值。编辑以添加请求的示例:
或者像这样:
You need to make sure that the reader is on the element before you can start getting attributes. However, unless you have a good reason to do so, you shouldn't need an
XmlReader
at all to get attribute values.Edited to add the requested example:
Or like this: