我遇到了一种独特的情况,我需要从XDocument中删除XElement,但是将父节点的值设置为null,因此,在调用fragment.Remove()时,出现了SystemInvalidOperation错误消息,那个“父母不见了”。
我正在遍历一个加载到XDocument中的.wxs文件,并且在该文件中有一个Wix根目录,并且XProcessingInstruction节点包含嵌套的XElement,这些XElements包含DescendantNodes()的集合。
using (SqlConnection strConnection = new SqlConnection(Connection))
{
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
var buttons = (new[] { groupBox1 }
.SelectMany(g => g.Controls.OfType<RadioButton>()
.Where(r => r.Checked)))
.ToList();
SqlCommand query = new SqlCommand();
if (buttons[0].Text == "Date Range")
{
query.CommandText = "Select * from [Sheet0$] where [ChangedDate] between @date1 and @date2;";
}
else
{
query.CommandText = "Select * from [Sheet0$]";
}
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand(query.CommandText, excelConnection))
{
if (buttons[0].Text == "Date Range")
{
string fromDate = this.fromDate.Value.Date.ToString("MM/dd/yyyy");
string toDate = this.toDate.Value.Date.ToString("MM/dd/yyyy");
cmd.Parameters.AddWithValue("@date1", fromDate);
cmd.Parameters.AddWithValue("@date2", toDate);
}
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection, SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null))
{
e.Result = 0;
sqlBulk.DestinationTableName = "tblCMHC";
while (dReader.Read())
{
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
}
我尝试先删除<Wix>
<?if condition ?>
<Fragment>
....
</Fragment>
<?endif?>
</Wix>
和<?if condition ?>
,因为<?endif?>
是它们的父节点,但是无论我是否接受,<Wix>
都会收到错误消息在XProcessingInstructions之前或之后将其删除。
如何正确删除片段元素?
答案 0 :(得分:1)
我没看到你的问题。考虑:
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<?if condition ?>
<Fragment></Fragment>
</Wix>
此代码:
XNamespace ns = "http://schemas.microsoft.com/wix/2006/wi";
string xmlTest = File.ReadAllText("test.wxs");
XDocument doc = XDocument.Parse(xmlTest);
doc.Descendants(ns + "Fragment").First().Remove();
Console.WriteLine(doc.ToString());
输出:
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<?if condition ?>
</Wix>