[英]Get Attribute Values using LINQ to XML with Unknown Elements
作为项目的一部分,我需要查询XML文件并根据搜索条件查找数据。 我已经尝试过使用XDocument
一些示例,但是我的问题是需要解析的XML文件大约有7种版本。 所以我不知道元素名称,只是文件可能包含哪些属性。 对于每个变体,我都将文件串联到一个文件中,这是我的理论,这会使搜索变得更加容易。 迄今为止,该理论已被证明是错误的。
全部将具有部分或全部属性列表。 例如
<root>
<T1>
<T11 name="123"/>
<H05 FileType="T52" ClientID="POB" />
</T1>
<T1>
<T11 name="1234"/>
<H05 FileType="T2" ClientID="POB" />
<E1 ErrorCode="AA00" ErrorText="There was an Error" />
<E1 ErrorCode="BB00" ErrorText="There was another Error" />
</T1>
</root>
如果我想要收集错误的搜索名称,是否可以仅使用文件中找到的属性名称使用LINQ进行搜索?
假设您要查找文档中包含ErrorCode
属性的所有节点:
XDocument document = LoadXml();
IEnumerable<XElement> errorNodes = document
// Find all descendant nodes:
.Descendants()
// With an "ErrorCode" attribute:
.Where(el => el.Attribute("ErrorCode") != null);
您应该能够执行这样的操作。
var xmlString = @"<root>
<T1>
<T11 name=""123\""/>
<H05 FileType=""T52"" ClientID=""POB"" />
</T1>
<T1>
<T11 name=""1234""/>
<H05 FileType=""T2"" ClientID=""POB"" />
<E1 ErrorCode=""AA00"" ErrorText=""There was an Error"" />
<E1 ErrorCode=""BB00"" ErrorText=""There was another Error"" />
</T1>
</root>";
var xml = XDocument.Parse(xmlString);
var names = from x in xml.Descendants().Attributes("name") select x.Parent;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.