So I was not at all willing to post it as already there are infinite documents about it. Its been 2years that I touched LINQ and now its taking a dig at me. After 3 hour of continuous try and failures, I decided to do what I was not willing to. Post it to SO.
I have this XML
<TopMost xmlns="http://abc.com/">
<Mine>MyName</Mine>
<Hello>
<File>SIMPLE</File>
<Book>20</Book>
<Copy>0</Copy>
</Hello>
</TopMost>
I just want to get values of “File”, “Book”, “Copy”. and want to compare it with something in Unit Test.
I reached upto this:
string result = string.Empty;
const string path = @"C:\Library.xml";
XDocument xdoc = XDocument.Load(path);
var lv1s = from paper in xdoc.Descendants("Hello")
select new
{
fileP = paper.Element("File").Value,
bookP = paper.Element("Book").Value,
copyP = paper.Element("Copy").Value,
};
result += lv1s.fileP + lv1s.bookP + lv1s.copyP; // Error
MessageBox.Show(result);
Error: Sequence contains no elements
I know there has to be a easy way around and I am far from it. I have many such code snippets that I have tried and failed.
EDIT
var lv1s = from paper in xdoc.Descendants(ns + "Hello")
select new
{
fileP = paper.Element(ns + "File").Value,
bookP = paper.Element(ns + "Book").Value,
copyP = paper.Element(ns + "Copy").Value,
};
I am getting Compilation error.
Error: The Name ns doex not exist in current context.
You need to specify the namespcae:
Don’t be tempted to use
string nsorvar ns.