我想读取下面的xml中的嵌套元素。到目前为止我已经能够读取chantier/data
元素中的数据,但是现在的问题在于如何才能读取<questions><sitePreparation> and <ctm>
里面的数据呢? Xml文件和代码已经缩短了一点,因为它们太长了。任何帮助深表感谢。如何读取使用Linq到xml的嵌套元素
<?xml version="1.0" encoding="UTF-8"?>
<Audit>
<controls>
<guid>
0001
</guid>
<templateVersion>
1.0
</templateVersion>
</controls>
<chantier>
<data>
<V2>V2</V2>
<V3>V3</V3>
<V3_1>V3_1</V3_1>
<V4>V4</V4>
<oresTiersPanel>
<S1_2>S1_2</S1_2>
</oresTiersPanel>
<agentsTiersPanel>
<S1_2_2>S1_2_2</S1_2_2>
</agentsTiersPanel>
</data>
<questions>
<sitePreparation>
<P1_Question>P1_Q</P1_Question>
<P6_Question>P6_Q</P6_Question>
</sitePreparation>
<ctm>
<C1_Question>C1_Q</C1_Question>
<C2_Question>C2_Q</C2_Question>
<C2_1>C2_1</C2_1>
</ctm>
</questions>
</chantier>
</Audit>
private static void ReadXml()
{
XDocument xdoc = XDocument.Load("sipp.xml");
if (xdoc.Root != null)
{
var chantier = from ch in xdoc.Root.Elements("chantier").Elements("data")
let agentsTiersPanel = ch.Element("agentsTiersPanel")
where agentsTiersPanel != null
select new
{
v2 = (string)ch.Element("V2"),
v3 = (string)ch.Element("V3"),
v3_1 = (string)ch.Element("V3_1"),
v4 = (string)ch.Element("V4"),
S1_2_2 = (string)agentsTiersPanel.Element("S1_2_2"),
S1_2_2_1 = (string)agentsTiersPanel.Element("S1_2_2_1"),
S1_2_3 = (string)agentsTiersPanel.Element("S1_2_3"),
S3 = (string)ch.Element("S3"),
S3_1 = (string)ch.Element("S3_1"),
P1_Question = (string)ch.Element("P1_Question")
};
foreach (var item in chantier)
{
Console.WriteLine(item.v2 + " " + item.v3);
}
}
}
如何读取数据的工作? –
请仔细阅读这些问题:http://stackoverflow.com/questions/13203975/how-to-parse-deeply-nested-using-linq-to-xml,http://stackoverflow.com/questions/11758904/accessing-嵌套元素通过LINQ到XML ...希望这会有所帮助..干杯! –
看起来不错。那么,阅读“问题”有什么问题?使用相同的方法 –