我是在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/但我还是想不出办法来做这件事。
答案 0 :(得分:1)
您可以使用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值分组 [编辑]导航到“变量”节点