This question must be easy, but I faced a problem, which I can't deal with. No matter what I try I am unable to parse this xml with linq and get the xml value.
The error is "System.Collections.Generic.IEnumerable' does not contain a definition for 'Element' and no extension method 'Element' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)"
I want to find the Xelement attribute.value which children have a concrete attribute.value. How can I get the attribute.value?
thanks
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>
code:
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));
This is one problem:
name = title1.Element("name").Value,
file= title1.Element("file").Value,
info= title1.Attribute("info").Value));
Look at your 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>
It doesn't have a name
or file
element - those are attributes. So you want something like:
string name = t1.Attribute("name");
string file = t1.Attribute("file");
string info = t1.Attribute("info");
Note that this is using t1
, not title1
- otherwise you're asking for the data from the query, rather than for the specific element of the query.
Additionally, you really don't need a query expression here. Just use:
var title1 = doc.Element("content").Element("submitInfo").Elements("setting");
Another problem is that you're currently calling string.Format
with three assignments inside. I suspect you actually wanted:
Console.WriteLine("{0} {1} {2}", t1.Attribute("name"),
t1.Attribute("file"), t1.Attribute("info"));
See more on this question at Stackoverflow