Why the string is always empty?
I try to use LINQ to read XML file. However, the string which store the value of selected attribute is always empty.
Here is the code:
string output = "";
XDocument loaded = XDocument.Load(@"d:\input.xml");
var ta = from tmp in loaded.Descendants("NewDataSet.Table")
select tmp.Element("E1");
开发者_C百科 foreach (string ss in ta)
{
ouput += ss;
}
The output
string is always empty. But the ss
string has correct value.
What is the problem?
I've no idea how to add xml file with style. So i have to update the xml file as image. :(
Now that you have shown your XML, here's how to fix your code:
var ta = from tmp in loaded.Descendants("Table")
select tmp.Element("E1");
You do not use .
in XML as you do in C# to navigate the XML tree. You could also navigate a XML tree using XPath:
var ta = from tmp in loaded.XPathSelectElements("NewDataSet/Table/E1")
select tmp;
Also I would recommend you to use a StringBuilder instead of string concatenations for this output variable:
var ta = from tmp in loaded.Descendants("Table")
select tmp.Element("E1");
var builder = new StringBuilder();
foreach (string ss in ta)
{
builder.Append(ss);
}
string output = builder.ToString();
var ta = from tmp in loaded.Descendants("Table")
select tmp.Element("E1");
精彩评论