C# 循环遍历 XML 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14806661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through XML document
提问by sujeesh
My XML file structure looks like this:
我的 XML 文件结构如下所示:
<SalaryDetails>
<Employee>
<Name>George Dsouza</Name>
<AnnualSalary>320000</AnnualSalary>
<DaysWorked>22</DaysWorked>
</Employee>
<Employee>
<Name>Hymanie Parera</Name>
<AnnualSalary>300000</AnnualSalary>
<DaysWorked>19</DaysWorked>
</Employee>
...
</SalaryDetails>
I want to put all the data into database as employe records using XmlDocument
.
我想将所有数据作为员工记录使用XmlDocument
.
So I wrote a loop like this:
所以我写了一个这样的循环:
XmlDocument xdcDocument = new XmlDocument();
xdcDocument.Load(@"D:\SalaryDetails.xml");
XmlElement xelRoot = xdcDocument.DocumentElement;
XmlNodeList xnlNodes = xelRoot.SelectNodes("/SalaryDetails/Employee");
foreach(XmlNode xndNode in xnlNodes)
{
//What to write here??
//My sql insert command will go here
}
AnnualSalary
and DaysWorked
are integers.
AnnualSalary
并且DaysWorked
是整数。
采纳答案by Shree
try:
尝试:
foreach (XmlNode xndNode in xnlNodes)
{
string name= xndNode ["Name"].InnerText;
string AnnualSalary= xndNode ["AnnualSalary"].InnerText;
string DaysWorked= xndNode ["DaysWorked"].InnerText;
//Your sql insert command will go here;
}
回答by Forhad Ahmed
xndNode contains an employee object with the Name, AnnualSalary and DaysWorked fields. It's just a matter of converting these into an SQL statment and inserting the row into a table in your database. The details would be database specific, but it should be something like this
xndNode 包含一个具有 Name、AnnualSalary 和 DaysWorked 字段的员工对象。只需将这些转换为 SQL 语句并将行插入数据库的表中即可。细节将是特定于数据库的,但它应该是这样的
insert into employee values (name, annual_salary, days_worked)
Assuming employees are keyed by name
假设员工按姓名键入
回答by masterlopau
You can also use XDoc and XElement to get the element values using the LINQ way. http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx
您还可以使用 XDoc 和 XElement 以使用 LINQ 方式获取元素值。http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx