更新时间:2023-11-24 12:34:28
为什么不通过DataSet读取它,如下所示。我修改了你的xml,因为将SQL放入注释中是没有意义的。
<?xml version =" 1.0"编码= QUOT; UTF-8英寸?>
< QUERIES>
< SQL ID =" Sheet1">
select * from file1
< / SQL>
< SQL ID =" Sheet2">
select * from file2
< / SQL>
< SQL ID =" Sheet3">
select * from file3
< / SQL>
< FILE> CUSTOMER< / FILE>
< / QUERIES>代码
var fileName = Path.Combine(AppDomain.CurrentDomain .BaseDirectory," xmlfile1.xml");
var ds = new DataSet();
ds.ReadXml(fileName);
var results = ds.Tables [" SQL"]
.AsEnumerable()
.Select(row => new
{
Id = row.Field< string>(" id"),
Statement = row.Field< string>(" SQL_TEXT")。Trim()
});
foreach(结果中的var项)
{
Console.WriteLine(
" {item.Id},{item。语句}");
}
Console.WriteLine(ds.Tables [&QUERIES"]
.AsEnumerable()
.Select(row => row) .Field< string>(" File"))
.FirstOrDefault());控制台写入行的结果。
Sheet1,select * from file1
Sheet2,select * from file2
Sheet3,select * from file3
CUSTOMER
This is my xml file
<?xml version="1.0" encoding="utf-8" ?> <QUERIES> <SQL ID="Sheet1"> <!-- select * from file1 --> </SQL> <SQL ID="Sheet2"> <!-- select * from file2 --> </SQL> <SQL ID="Sheet3"> <!-- select * from file3 --> </SQL> <FILE>CUSTOMER</FILE> </QUERIES>
XDocument xml1 = XDocument.Load(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) +"\\Sql.xml"); List<string> sql_strings1 = ((IEnumerable<object>)xml1.XPathEvaluate("/*/SQL/comment()")) .Cast<XComment>() .Select(c => c.Value.Trim()) .ToList();
How can I get the value ID sheet1, sheet2, sheet3 in a lis<string> variable from Xdocument xml1. Also How can I get the tag name <FILE>CUSTOMER</FILE> in string variable
Please help
polachan
Why not make it simple by reading via a DataSet as shown below. I altered your xml as placing SQL into comments does not make sense.
<?xml version="1.0" encoding="utf-8" ?> <QUERIES> <SQL ID="Sheet1"> select * from file1 </SQL> <SQL ID="Sheet2"> select * from file2 </SQL> <SQL ID="Sheet3"> select * from file3 </SQL> <FILE>CUSTOMER</FILE> </QUERIES>Code
var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "xmlfile1.xml"); var ds = new DataSet(); ds.ReadXml(fileName); var results = ds.Tables["SQL"] .AsEnumerable() .Select(row => new { Id = row.Field<string>("id"), Statement = row.Field<string>("SQL_TEXT").Trim() }); foreach (var item in results) { Console.WriteLine(
"{item.Id}, {item.Statement}"); } Console.WriteLine(ds.Tables["QUERIES"] .AsEnumerable() .Select(row => row.Field<string>("File")) .FirstOrDefault());Results from console write line.
Sheet1, select * from file1 Sheet2, select * from file2 Sheet3, select * from file3 CUSTOMER