这是我的XML文件:
<?xml version="1.0" standalone="no" ?>
<!-- This file represents The Details of the user and the responces: -->
<Survey>
<Clientdetails>
<ClientName xmlns="yash" />
<ClientCompanyName xmlns="lnt" />
<ClientTelNo. xmlns="546" />
<ClientMobileNo xmlns="56" />
<ClientEMail xmlns="56" />
</Clientdetails>
<ClientResponces>
<Question1>
<responce>1</responce>
</Question1>
<Question2>
<responce>2</responce>
</Question2>
<Question3>
<responce>3</responce>
</Question3>
<Question4>
<responce>3</responce>
</Question4>
<Question5>
<Question5.1>
<responce>3</responce>
</Question5.1>
<Question5.2>
<responce>3</responce>
</Question5.2>
<Question5.3>
<responce>2</responce>
</Question5.3>
<Question5.4>
<responce>3</responce>
</Question5.4>
<Question5.5>
<responce>3</responce>
</Question5.5>
<Question5.6>
<responce>3</responce>
</Question5.6>
<Question5.7>
<responce>3</responce>
</Question5.7>
<Question5.8>
<responce>2</responce>
</Question5.8>
<Question5.9>
<responce>1</responce>
</Question5.9>
<Question5.10>
<responce>2</responce>
</Question5.10>
<Question5.11>
<responce>0</responce>
</Question5.11>
<Question5.12>
<responce>0</responce>
</Question5.12>
<Question5.13>
<responce>0</responce>
</Question5.13>
<Question5.14>
<responce>0</responce>
</Question5.14>
<Question5.15>
<responce>0</responce>
</Question5.15>
<Question5.16>
<responce>0</responce>
</Question5.16>
<Question5.17>
<responce>0</responce>
</Question5.17>
</Question5>
</ClientResponces>
</Survey>
我想将这些数据读入DataSet。我只想要客户给出的回复,对于第5个问题,我想要17个子问题的平均值。
例如,DataSet应该只包含:
1
2
3
3
4
如何在C#中执行此操作?
答案 0 :(得分:3)
那个xml很漂亮......太可怕了。我的第一个建议是通过xslt转换运行它以使其更正常,可以加载Load
。目前,它滥用名称空间可怕。
或者,忘记DataSet
,然后使用XmlDocument
或类似内容进行解析。
这是一种使用XmlDocument
的方法(并且仅使用LINQ来保存平均值,以节省几行代码):
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlElement el in doc.SelectNodes("//responce")) {
Console.WriteLine(el.ParentNode.Name + "=" + el.InnerText);
}
XmlNodeList fiveAnswers = doc.SelectNodes(
"/Survey/ClientResponces/Question5/*/responce");
double avg = fiveAnswers.Cast<XmlElement>()
.Average(el => int.Parse(el.InnerText));
Console.WriteLine(avg);
例如 normal xml:
<question num="1">
<response>1</response>
</question>
...
<question num="5">
<response num="1">1</response>
<response num="2">3</response>
...
</question>
或类似的东西。不要使用元素名称来推断身份。
答案 1 :(得分:1)
尝试
XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml(<your string>);
DataSet ds = doc.DataSet;
然后,您可以使用LINQ从文档中选择不同的内容。
更新
foreach (XmlNode node in doc.SelectNodes("\\Survey\ClientResponses"))
{
string text = node.InnerText;
}
(未经过测试!你的嵌套案例会很棘手!)