我有一个XML文件,我想读取它并将结果保存到数据表中,这是我的XML文件:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table name="tblAdminUser">
<Column>
<displayname>
Created Date
</displayname>
<orignalvalue>
Created_Date
</orignalvalue>
</Column>
<Column>
<displayname>
First Name
</displayname>
<orignalvalue>
F_Name
</orignalvalue>
</Column>
</Table>
<Table name="test1">
<Column>
<displayname>
Last Name
</displayname>
<orignalvalue>
L_Name
</orignalvalue>
</Column>
<Column>
<displayname>
Created By
</displayname>
<orignalvalue>
Created_By
</orignalvalue>
</Column>
</Table>
</NewDataSet>
现在我想做的是:
如果“表”节点的“名称”是“ tblAdminuser”,那么我想在两列的数据表中获取“显示列”节点的内部值和相应的“原始值”。
我到目前为止所做的是:
XmlDataDocument xmldoc = new XmlDataDocument();
xmldoc.Load(Server.MapPath("~/XMLFile.xml"));
XmlElement root = xmldoc.DocumentElement;
XmlNodeList tablenodes = root.SelectNodes("Table");
foreach (XmlNode nodes in tablenodes)
{
if (nodes.LocalName == "tblAdminUser")
{
XmlNodeList Columnnodes = root.SelectNodes("Column"); // You can also use XPath here
XmlNodeList displayColumnnodes = root.SelectNodes("Column");
foreach (XmlNode node in displayColumnnodes)
{
Response.Write(node.InnerText);
// use node variable here for your beeds
}
}
}
请帮我。
最佳答案
尝试这个
XmlDataDocument xmldoc = new XmlDataDocument();
xmldoc.Load("C:/test.xml");
var root = xmldoc.DocumentElement;
if (root == null) return;
var users = new List<User>();
var tablenodes = root.SelectNodes("Table");
if (tablenodes != null)
foreach (XmlNode nodes in tablenodes)
{
if (!nodes.HasChildNodes) continue;
if (nodes.Attributes == null) continue;
var user = new User { UserName = nodes.Attributes[0].Value };
var customer = new Customer();
var nodesdisplayname = nodes.SelectNodes("Column/displayname");
if (nodesdisplayname != null)
{
var xmlNode = nodesdisplayname.Item(0);
if (xmlNode != null)
{
customer.DisplayName = xmlNode.InnerText;
}
}
var nodesorignalvalue = nodes.SelectNodes("Column/orignalvalue");
if (nodesorignalvalue != null)
{
var xmlNode = nodesorignalvalue.Item(0);
if (xmlNode != null)
{
customer.OriginalValue = xmlNode.InnerText;
}
}
user.Customers = customer;
users.Add(user);
}
还要在上面的代码中添加条件为
if(nodes.Attributes[0].Value == "tblAdminUser")
{
// Added code here
}
并以用户和客户类别为例
public class User
{
public Customer Customers;
public string UserName { get; set; }
}
public class Customer
{
public string DisplayName { get; set; }
public string OriginalValue { get; set; }
}
它将返回用户列表。
我想这会有所帮助。