2012-10-22 69 views
2

我有一个XML文件:TableList.xml查询XML文件,并创建一个文本文件

<TableList> 
<Table> 
<TableName>TableA</TableName> 
<Columns>ColumnA1,ColumnA2,ColumnA3,ColumnA4</Columns> 
</Table> 
<Table> 
<TableName>TableB</TableName> 
<Columns>ColumnB1,ColumnB2,ColumnB3,ColumnB4</Columns> 
</Table> 
</TableList> 

我想查询使用LINQ到XML和每个值的我想要得到下面这个文件格式

The table - TableA - has columns - ColumnA1,ColumnA2,ColumnA3,ColumnA4. 

The table - TableB - has columns - ColumnB1,ColumnB2,ColumnB3,ColumnB4. 

并将其创建为单个文本文件 - TableDoc.txt - 最后。

这怎么可以用简洁的圆顶来使用Linq-to-XML?

回答

5

这怎么可以用简洁的圆顶来使用Linq-to-XML?

我会将此作为一个简洁的挑战......

File.WriteAllLines("TableDoc.txt", XDocument.Load("TableList.xml") 
     .Descendants("Table") 
     .Select(t => string.Format("The table - {0} - has columns {1}.", 
            t.Element("TableName").Value, 
            t.Element("Columns").Value))); 

(显然,删除所有不必要的空白为真正简洁。)

这仍然留下您的挑战弄清楚它是如何/为什么会起作用的 - 当然也可能以更可读的方式重构它。

+1

对于legand +1和 – Anirudha

+0

+1也是。 –

1
using (TextWriter writer = File.CreateText("TableDoc.txt")) 
{ 
    XDocument doc=XDocument.Load("yourXML");//load document 
    foreach(var elm in doc.Descendants("Table"))//takes all table elements 
    { 
    string s="The table-"+elm.Element("TableName").Value+"- has coloumns -"+elm.Element("Columns").Value; 
     writer.WriteLine(s); 
    } 
} 
1

可能我建议稍微更可读的查询表达式版本(主观):

var columnsPerTable = from table in XElement.Load("TableList.xml").Elements("Table") 
         let name = table.Element("TableName") 
         let columns = table.Element("Columns") 
         select string.Format("The table - {0} - has columns - {1}.", 
              name.Value, columns.Value); 
File.WriteAllLines("TableDoc.txt", columnsPerTable); 

没有必要使用一个XDocument,当然。 XElement工作得很好。