[英]Get value in xml from c#
这个问题一定很容易,但是我遇到了一个我无法解决的问题。 无论我尝试什么,我都无法使用linq解析此xml并获取xml值。
错误为“ System.Collections.Generic.IEnumerable”不包含“元素”的定义,并且找不到扩展方法“元素”接受类型为“ System.Collections.Generic.IEnumerable”的第一个参数(您是否丢失了?使用指令或程序集引用?)”
我想找到Xelement attribute.value,它的孩子有一个具体的attribute.value。 如何获取attribute.value?
谢谢
XML文件
<submitInfo>
<setting name="file1" file ="example3.c" info ="open it!" serializeAs="String">
<add name="file11" program="example2.c" />
<add name="file12" value="example1.c" />
<value />
<setting name="file2" file ="example23.c" info ="open it!" serializeAs="String">
<add name="file21" program="example22.c" />
<add name="file22" value="example21.c" />
<value />
</setting>
</submitInfo>
码:
var title1 = from q in doc.Element("content").Element("submitInfo").Elements("setting")
select q;
foreach (var t1 in title1)
{
Console.WriteLine(
String.Format(
name = title1.Element("name").Value,
file= title1.Element("file").Value,
info= title1.Attribute("info").Value));
}
//get setting info
var title = from p in doc.Element("content").Element("submitInfo").Element("setting").Elements("add")
select p;
foreach (var t1 in title)
{
Console.WriteLine(
String.Format(
name = title1.Element("name").Value,
value = title1.Element("program").Value));
这是一个问题:
name = title1.Element("name").Value,
file= title1.Element("file").Value,
info= title1.Attribute("info").Value));
查看您的XML:
<setting name="file1" file ="example3.c" info ="open it!" serializeAs="String">
<add name="file11" program="example2.c" />
<add name="file12" value="example1.c" />
<value />
</setting>
它没有name
或file
元素-它们是属性。 所以你想要像这样的东西:
string name = t1.Attribute("name");
string file = t1.Attribute("file");
string info = t1.Attribute("info");
请注意,这使用的是t1
,而不是title1
否则,您要从查询中获取数据,而不是查询中的特定元素。
此外,您在这里确实不需要查询表达式。 只需使用:
var title1 = doc.Element("content").Element("submitInfo").Elements("setting");
另一个问题是您当前正在调用string.Format
其中包含三个分配。 我怀疑您实际上想要的是:
Console.WriteLine("{0} {1} {2}", t1.Attribute("name"),
t1.Attribute("file"), t1.Attribute("info"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.