使用LINQ XML查询属性值
本文关键字:属性 查询 XML LINQ 使用 | 更新日期: 2023-09-27 18:12:29
我是用c#查询XML文件的新手。任何帮助都会很感激。提前感谢……
我有这个XML文件:
<Point>
<Statement>
<Type />
<FullCondtion />
<ExpressionList />
</Statement>
<TestList>
<Test>
<Inputs>
<Variable Name="u1_count" Value="0" />
<Variable Name="u1_flag" Value="2" />
<Variable Name="ON" Value="1" />
<Variable Name="OFF" Value="0" />
<Variable Name="u1_ch" Value="0" />
<Variable Name="u1_index" Value="3" />
</Inputs>
<Outputs>
<Variable Name="u1_count" Value="0" />
<Variable Name="u1_flag" Value="0" />
<Variable Name="ON" Value="1" />
<Variable Name="OFF" Value="0" />
<Variable Name="u1_ch" Value="0" />
<Variable Name="u1_index" Value="0" />
</Outputs>
</Test>
<Test>
<Inputs>
<Variable Name="u1_count" Value="0" />
<Variable Name="u1_flag" Value="2" />
<Variable Name="ON" Value="1" />
<Variable Name="OFF" Value="0" />
<Variable Name="u1_ch" Value="0" />
<Variable Name="u1_index" Value="3" />
</Inputs>
<Outputs>
<Variable Name="u1_count" Value="0" />
<Variable Name="u1_flag" Value="0" />
<Variable Name="ON" Value="1" />
<Variable Name="OFF" Value="0" />
<Variable Name="u1_ch" Value="0" />
<Variable Name="u1_index" Value="0" />
</Outputs>
</Test>
</TestList>
<TestList>
<Test>
<Inputs>
<Variable Name="u1_count" Value="0" />
<Variable Name="u1_flag" Value="2" />
<Variable Name="ON" Value="1" />
<Variable Name="OFF" Value="0" />
<Variable Name="u1_ch" Value="0" />
<Variable Name="u1_index" Value="3" />
</Inputs>
<Outputs>
<Variable Name="u1_count" Value="0" />
<Variable Name="u1_flag" Value="0" />
<Variable Name="ON" Value="1" />
<Variable Name="OFF" Value="0" />
<Variable Name="u1_ch" Value="0" />
<Variable Name="u1_index" Value="0" />
</Outputs>
</Test>
<Test>
<Inputs>
<Variable Name="u1_count" Value="0" />
<Variable Name="u1_flag" Value="2" />
<Variable Name="ON" Value="1" />
<Variable Name="OFF" Value="0" />
<Variable Name="u1_ch" Value="0" />
<Variable Name="u1_index" Value="3" />
</Inputs>
<Outputs>
<Variable Name="u1_count" Value="0" />
<Variable Name="u1_flag" Value="0" />
<Variable Name="ON" Value="1" />
<Variable Name="OFF" Value="0" />
<Variable Name="u1_ch" Value="0" />
<Variable Name="u1_index" Value="0" />
</Outputs>
</Test>
</TestList>
</Point>
</Pattern>
</CodeAnalyzerResults>
我需要将输入和输出中的变量及其值写入表中,如下所示:
输入u1_count 0 0 0 0
u1_flag 2 2 2 2
…
u1_index 3 3 3 3
,输出也是如此。我如何获得每个变量的输入和输出值并将它们写在一行中?
我读了这篇文章:http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/reading-xml-file-through-linq-a-few-tips/但我仍然想不出一个方法来做…
您可以使用LINQ to XML (system . XML)。Linq组装)
XDocument doc = XDocument.Load("xml uri");
IEnumerable<string> inputs =
from input in doc.Descendants("Inputs")
from el in input.Descendants("Variable")
let nameAtt = el.Attribute("Name")
let valueAtt = el.Attribute("Value")
where nameAtt != null && valueAtt != null
group valueAtt.Value by nameAtt.Value into grp
let values = string.Join(" ", grp.ToArray())
select string.Format("{0} {1}", grp.Key, values);
对于outputs
也是如此。
[编辑]分组由att值[编辑]导航到"Variables"节点