假设我有下一个xml:
<Report>
<File id="1">
<Variables>
<Variable id="1" name="integer"> 1 </Variable>
<Variable id="1" name="string"> x </Variable>
</Variables>
</File>
<File id="2">
<Variables>
<Variable id="2" name="integer"> 1 </Variable>
<Variable id="2" name="string"> x </Variable>
</Variables>
</File>
<File id="3">
<Variables>
<Variable id="3" name="integer"> 1 </Variable>
<Variable id="3" name="string"> y </Variable>
</Variables>
</File>
如何获取变量字符串为“x”的所有文件?
注意linq到xml vb或c#但是vb是首选
答案 0 :(得分:2)
假设您已将XML加载到XDocument
实例,您可以执行以下操作:
var files = from f in xDoc.Root.Elements("File")
where f.Element("Variables")
.Elements("Variable")
.Any(v => (string)v.Attribute == "string" &&
(string)v == "x")
select f;
或使用等效的基于方法的查询:
var files = xDoc.Root.Elements("File")
.Where(f => f.Element("Variables")
.Elements("Variable")
.Any(v => (string)v.Attribute == "string" &&
(string)v == "x"))
答案 1 :(得分:0)
给出以下xml:
Dim xml = <Report>
<File id="1">
<Variables>
<Variable id="1" name="integer">1</Variable>
<Variable id="1" name="string">x</Variable>
</Variables>
</File>
<File id="2">
<Variables>
<Variable id="2" name="integer">1</Variable>
<Variable id="2" name="string">x</Variable>
</Variables>
</File>
<File id="3">
<Variables>
<Variable id="3" name="integer">1</Variable>
<Variable id="3" name="string">y</Variable>
</Variables>
</File>
</Report>
你可以使用Linq:
Dim result = xml.<File> _
.Where(Function(file) file.<Variables>.<Variable> _
.Any(Function(variable) variable.@name = "string" AndAlso
variable.Value = "x"))
或更短,使用XPath-Expression查询节点:
Dim doc = New XmlDocument() ' Use XmlDocument instead of XElement '
doc.LoadXml(xml.ToString())
Dim result = doc.SelectNodes("/Report/File[Variables/Variable[@name='string' and text()='x']]")