我有这个xml文件,现在我想在我的xml文件中添加新条目
之前:
<?xml version="1.0" encoding="utf-8"?>
<email>
<builderemail>
<builder>
<id>1</id>
<value>builder@xyz.com</value>
</builder>
</builderemail>
<manageremail>
<manager>
<id>1</id>
<value>manager@xyz.com</value>
</manager>
</manageremail>
</email>
后:
<?xml version="1.0" encoding="utf-8"?>
<email>
<builderemail>
<builder>
<id>1</id>
<value>builder@xyz.com</value>
<id>2</id>
<value>Others</value>
</builder>
</builderemail>
<manageremail>
<manager>
<id>1</id>
<value>manager@xyz.com</value>
<id>2</id>
<value>Others</value>
</manager>
</manageremail>
</email>
我的代码c#代码:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Visible = false;
Button1.Visible = false;
TextBox2.Visible = false;
Button2.Visible = false;
if (!IsPostBack)
{
PopulateDDLFromXMLFile();
}
}
public void PopulateDDLFromXMLFile()
{
DataSet ds = new DataSet();
ds.ReadXml(MapPath("~/App_Data/builderemail.xml"));
//get the dataview of table "Country", which is default table name
DataView dv = ds.Tables["builder"].DefaultView;
DataView dw = ds.Tables["manager"].DefaultView;
//or we can use:
//DataView dv = ds.Tables[0].DefaultView;
//Now sort the DataView vy column name "Name"
dv.Sort = "value";
//now define datatext field and datavalue field of dropdownlist
DropDownList1.DataTextField = "value";
DropDownList1.DataValueField = "ID";
DropDownList2.DataTextField = "value";
DropDownList2.DataValueField = "ID";
//now bind the dropdownlist to the dataview
DropDownList1.DataSource = dv;
DropDownList1.DataBind();
DropDownList2.DataSource = dw;
DropDownList2.DataBind();
}
然而,这不起作用。我将收到IndexOutOfRangeException错误。我该如何处理?
答案 0 :(得分:0)
“IndexOutOfRange”异常是因为这行代码:
dv.Sort = "value"; //because the Table "builder" doesn't have the "value" column
PopulateDDLFromXMLFile方法适用于xml的第一个版本。 xml的更高版本不是有效版本,并不表示您希望/尝试在PopulateDDLFromXMLFile方法中执行的操作。
DataSet ds = new DataSet();
ds.ReadXml(MapPath("~/App_Data/builderemail.xml"));
在较新的xml上调用上面的代码会创建6个表,一个用于builderemail,builder,id,value,manageremail和manager。
但是代码假定id和value是builder表中的列。 因此上述例外。
我建议您将xml修改为:
<?xml version="1.0" encoding="utf-8" ?>
<email>
<builderemail>
<builder>
<id>1</id>
<value>builder@xyz.com</value>
</builder>
<builder>
<id>2</id>
<value>Others</value>
</builder>
</builderemail>
<manageremail>
<manager>
<id>1</id>
<value>manager@xyz.com</value>
</manager>
<manger>
<id>2</id>
<value>Others</value>
</manger>
</manageremail>
</email>